您的位置:首页 > 其它

Minimum Depth of Binary Tree & Maximum Depth of Binary Tree

2014-08-26 16:47 453 查看
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;   //空树,直接返回0
if( !root->left & !root->right ) return 1;  //如果是只有一个节点,则是1层
int left = minDepth(root->left);    //求左子树的高度
int right = minDepth(root->right);  //求右子树的高度
if( left == 0 ) return right + 1;   //如果左子树为空
if( right == 0 ) return left + 1;   //如果右子树为空
return min(left, right) + 1;    //返回左右子树中小的高度再加1
}
};


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

/**
* 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;
queue<TreeNode*> qt;
qt.push(root);
qt.push(NULL);
int level = 1;
while( !qt.empty() ) {
TreeNode* cur = qt.front();
qt.pop();
if( cur ) {
if( !cur->left && !cur->right ) break;  //如果当前节点就是叶节点,直接跳出循环
if( cur->left ) qt.push(cur->left);
if( cur->right ) qt.push(cur->right);
}
else {
if( !qt.empty() ) qt.push(NULL);    //如果队列不为空,则加入层标志
++level;    //进入下一层
}
}
return level;
}
};


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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: