Minimum Depth of Binary Tree(C++二叉树的最小深度)

解题思路:

(1)使用递归

(2)注意一个节点的最低高度为左右子树的最低高度+1

(3)注意如果其中一个子树的高度为0,那么另一个子树的高度+1为该结点的最小高度

/**
 * Definition for a binary tree node.
 * 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 dfs(root);
        else return 0;
    }

private:
    int dfs(TreeNode* node) {
        int l = node->left ? dfs(node->left) : 0;
        int r = node->right ? dfs(node->right) : 0;
        if (l==0) return r+1;
        if (r==0) return l+1;
        else return min(l,r)+1;
    }
};
发布了303 篇原创文章 · 获赞 277 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/coolsunxu/article/details/105531658