二叉树的最小深度

来源:互联网 发布:mac需要安装flash插件 编辑:程序博客网 时间:2024/06/05 14:15
问题描述:

给定一个二叉树,找出其最小深度。

二叉树的最小深度为根节点到最近叶子节点的距离。

样例

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

这个二叉树的最小深度为 2

解题思路:通过递归,记录左子树的最小深度以及右子树的最小深度,当某节点的左右子树有一个为空,另一个不为空时,递归结束。

实验代码:

class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int minDepth(TreeNode *root) {
        // write your code here
        if(root==NULL) return 0;
        if(root->left==NULL&&root->right!=NULL) return minDepth(root->right)+1;
        if(root->left!=NULL&&root->right==NULL) return minDepth(root->left)+1;
        int l = minDepth(root->left);
        int r = minDepth(root->right);
        if(l<r)return l+1;
        return r+1;
    }
};

个人感想:不需要考虑左右子树都不为空的情况,递归时遇到这种情况可以继续递归下去。

0 0