[LeetCode111] 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.

分类:Tree BFS DFS

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int minDepth(TreeNode* root) {
13         if(!root)
14             return 0;
15         int leftDepth = minDepth(root->left);
16         int rightDepth = minDepth(root->right);
17         //有一个为空 选取存在的叶子节点
18         if(!root->left || !root->right)
19             return leftDepth < rightDepth ? rightDepth + 1 : leftDepth + 1;
20         return leftDepth < rightDepth ? leftDepth + 1 : rightDepth + 1;
21     }
22 };

 

posted @ 2016-08-16 11:14  zhangbaochong  阅读(175)  评论(0编辑  收藏  举报