leetcode-1-二叉树的最小深度

leetcode-1-二叉树的最小深度

    • solution1:层次遍历/BFS广度优先
    • solution2:递归

minimum depth of binary tree

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
leetcode-1-二叉树的最小深度_第1张图片

class solution{
public:
	int run(TreeNode* root){
	}
}

solution1:层次遍历/BFS广度优先

层次遍历,遇到的第一个节点也是最浅的
对于二叉树来说,层次遍历和BFS是等价的。
层次遍历/BFS.

class Solution {
public:
    typedef TreeNode* tree;//因为要用到队列,STL队列是一个容器,要定义容器的类型,这里定义容器要用到的类型定义
    int run(TreeNode *root) 
    {
        if(root == nullptr)
            return 0;
            //空树
        queue<tree> qu;
        tree last , now;//队列中的最后一个元素和第一个元素
        int level , size;//当前层数和队列大小
        last = now = root;//初始化队列游标
        level = 1;//既然树不为空,level至少为1
        qu.push(root);//根入队
        while(qu.size())//只要队列不为空
        {
            now = qu.front();//取出第一个节点
            qu.pop();//把它弹出队列
            size = qu.size();//更新队列大小
            //该节点孩子加到队列中
            if(now->left)
                qu.push(now->left);
            if(now->right)
                qu.push(now->right);
            //如果队列大小没变,没孩子,是子节点
            if(size - qu.size() == 0)
                break;//this node has no child. it's the first node I meet.
            if(now == last)
            {
            //这一层的头与尾汇合了
                level++;
                if(qu.size() != 0)//这个似乎没用
                //到下一层
                    last = qu.back();
            }
        }
        return level;
        
    }
    
    
};

solution2:递归

就是短
递归

class Solution {
public:
    int run(TreeNode *root)
    {
    	//若是空树返回0
        if (root == nullptr)
            return 0;
        //如果左子树为空,返回右子树+1
        if(root->left == nullptr)
            return run(root->right)+1;
        //如果右子树为空,返回左子树+1
        if(root->right == nullptr)
            return run(root->left)+1;
        //如果儿女双全,返回较小的一个;
        int leftDepth = run(root->left);
        int rightDepth = run(root->right);
        return (leftDepth < rightDepth) ? leftDepth+1 : rightDepth+1;
    }
};

做个简单题这么费劲 哭了

你可能感兴趣的:(leetcode)