现在的位置: 首页 > 综合 > 正文

leetcode:Minimum Depth of Binary Tree(树的根节点到叶子节点的最小距离)【面试算法题】

2013年01月05日 ⁄ 综合 ⁄ 共 498字 ⁄ 字号 评论关闭

题目:

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 binary tree
 * 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 0;
        int a=minDepth(root->right);
        int b=minDepth(root->left);
        if(a*b!=0)return min(a,b)+1;
        else if(b==0)return a+1;
        else if(a==0) return b+1;
    }
};

抱歉!评论已关闭.