二叉树最短路径

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.
class Solution {
public:
    int run(TreeNode *root) {
        if(root==NULL) return 0;
        if(root->left==NULL&&root->right==NULL) return 1;
        if(root->left==NULL)
            return run(root->right)+1;
        else if(root->right==NULL)
            return run(root->left)+1;
        else 
            return 1+min(run(root->right),run(root->left));
    }
};

将问题分解成 1.判断当前结点是否为空,是否有子节点 2.如果仅存在左子节点,返回左子节点下的最短路径;如果仅存在右子节点,返回右子节点下的最短路径;如果左右子节点都存在,返回左右子节点各自最短路径之间较小的那个。

猜你喜欢

转载自blog.csdn.net/fuck_you_sb/article/details/79971924
今日推荐