二叉树的最小深度

来源:互联网 发布:沃尔什变换矩阵 编辑:程序博客网 时间:2024/04/30 09:29

问题描述:给定一个二叉树,找出其最小深度。二叉树的最小深度为根节点到最近叶子节点的距离。

样例

给出一棵如下的二叉树:

        1

     /     \ 

   2       3

          /    \

        4      5  

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


思路:递归的思想。求二叉树的最小深度,就到NULL的 时候停止,那么就要考虑左右子树为空的情况。当左子树为NULL时,root移动到右子树,再加1。右子树相同。

利用递归重复上一步骤。

代码:/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
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) return minDepth(root->right)+1;
        if(root->right==NULL) return minDepth(root->left)+1;
        else{int l=minDepth(root->left);
             int r=minDepth(root->right);
             int m=min(l,r)+1;
             return m;
        }

    }
};

思想:还是递归的的思想,还要考虑问题的全面性。

0 0
原创粉丝点击