• leetcode Minimum Depth of Binary Tree


    题目:返回根节点到最近的叶子节点的距离。

    例如:{1,2},其中2是1的左子树,1的右子树为空,2为叶子节点,那么此时返回2.

    如果用简单的递归,以为是返回左右两边的最小值加1,那么上面那个case就错了,因为如果返回左右两边最小值加1的话,上面1的右边是0,所以返回1,但我们想要的是2.

    所以要另外注意递归的返回条件。

    也就是如果是叶节点了那就返回1,不为空的时候才递归,详见代码:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode *root) {
            if (!root) return 0;
            if (!root -> left && !root -> right) return 1;
            int lf = INT_MAX, ri = INT_MAX;
            if (root -> left)
                lf = minDepth(root -> left);
            if (root -> right)
                ri = minDepth(root -> right);
            return min(lf, ri) + 1;
        }
    };

     或者是:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int minDepth(TreeNode *root) {
            if(!root)return 0;
            int a=minDepth(root->right);
            int b=minDepth(root->left);
            if(a*b!=0)return min(a,b)+1;
            else if(b==0)return a+1;
            else if(a==0) return b+1;
        }
    };

     同时记录一下非递归的解法:

    public int minDepth(TreeNode root) {
            if(root == null)
                return 0;
            
            int depth = 1;//The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
            LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            int curnum = 1;
            int nextnum = 0;
            while(!queue.isEmpty()){
                TreeNode cur = queue.poll();
                curnum--;
                
                if(cur.left == null && cur.right == null)
                    return depth;
                
                if(cur.left != null){
                   queue.add(cur.left);
                   nextnum++;
                }
                
                if(cur.right != null){
                    queue.add(cur.right);
                    nextnum++;
                }
                
                if(curnum == 0){
                    curnum = nextnum;
                    nextnum = 0;
                    depth++;
                }
            }
            return depth;
        }
  • 相关阅读:
    xp 安装 win7 64
    局域网内传输文件速度慢
    安全和共享设置
    vs2005无法启动
    dos快速通道
    xp 共享 guest
    Java菜题
    Java序列化总结(最全)
    Bitset改进你的程序质量
    Java反射方法总结
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4132282.html
Copyright © 2020-2023  润新知