1. 程式人生 > >leetcode:Minimum Depth of Binary Tree(樹的根節點到葉子節點的最小距離)【面試演算法題】

leetcode:Minimum Depth of Binary Tree(樹的根節點到葉子節點的最小距離)【面試演算法題】

題目:

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;
    }
};