Minimum Depth of Binary Tree & Maximum 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.

 

方法一:后序遍历这颗树,先分别求出左右两颗子树的高度,在取最小,代码如下:

 1 /**
 2  * Definition for binary tree
 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 ) return 0;   //空树,直接返回0
14         if( !root->left & !root->right ) return 1;  //如果是只有一个节点,则是1层
15         int left = minDepth(root->left);    //求左子树的高度
16         int right = minDepth(root->right);  //求右子树的高度
17         if( left == 0 ) return right + 1;   //如果左子树为空
18         if( right == 0 ) return left + 1;   //如果右子树为空
19         return min(left, right) + 1;    //返回左右子树中小的高度再加1
20     }
21 };

 

方法二:层次遍历这颗数,并记录当前节点所在的层,先访问到叶节点是,这时的层数就是最小的root到叶节点的路径,代码如下:

 1 /**
 2  * Definition for binary tree
 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 ) return 0;
14         queue<TreeNode*> qt;
15         qt.push(root);
16         qt.push(NULL);
17         int level = 1;
18         while( !qt.empty() ) {
19             TreeNode* cur = qt.front();
20             qt.pop();
21             if( cur ) {
22                 if( !cur->left && !cur->right ) break;  //如果当前节点就是叶节点,直接跳出循环
23                 if( cur->left ) qt.push(cur->left);
24                 if( cur->right ) qt.push(cur->right);
25             }
26             else {
27                 if( !qt.empty() ) qt.push(NULL);    //如果队列不为空,则加入层标志
28                 ++level;    //进入下一层
29             }
30         }
31         return level;
32     }
33 };

 

Maximum Depth of Binary Tree也可以使用上述方法

posted on 2014-08-26 16:47  bug睡的略爽  阅读(122)  评论(0)    收藏  举报

导航