• [LeetCode]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.

    思考:考虑[1,2]这种情况,返回树最低高度为2。所以分两种情况,有一棵子树不在时,返回另一棵子树树高+1,否则返回矮子树高+1.

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

      

  • 相关阅读:
    UITextField的总结
    【实战】登录界面
    点分治学习
    2020/3/1
    2020/2/29
    2020/2/28
    2020/2/27
    2020/2/27
    最小树形图
    Ch’s gift HDU6162
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3459306.html
Copyright © 2020-2023  润新知