leetcode--111. Minimum Depth of Binary Tree

来源:互联网 发布:用c语言制作病毒 编辑:程序博客网 时间:2024/05/21 05:44

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.

题解

和求最大深度类似,不过求最小深度需要注意的是,当一个节点只有左子树或者右子树的时候,不应取最小的那个作为深度。

/** * 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 == NULL) return 0;        int L = minDepth(root->left), R = minDepth(root->right);        return 1 + (min(L, R) ? min(L, R) : max(L, ;R))    }};
0 0
原创粉丝点击