二叉樹最小深度探究
阿新 • • 發佈:2018-11-26
一、求解最小深度
題目是這樣描述的: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、採用遞迴的方法:
class Solution {
public:
int run(TreeNode *root) {
if(root == NULL)
return 0;
if(root->left == NULL && root->right == NULL)
return 1;
int leftDepth = run(root->left);
if(leftDepth == 0)
leftDepth = INT_MAX;//防止左孩子為空,帶來的影響
int rightDepth = run(root->right);
if(rightDepth == 0)
rightDepth = INT_MAX;//防止右孩子為空,帶來的干擾
return leftDepth < rightDepth ? (leftDepth + 1) : (rightDepth + 1);
}
};
//另外一種寫法:
class Solution {
public:
int minDepth(TreeNode *root) {
if (root == NULL) return 0;//根節點為空的情況
if (root->left == NULL && root->right == NULL) return 1 ;//沒有左右孩子的情況
if (root->left == NULL) return minDepth(root->right) + 1;//沒有左孩子,只有右孩子的情況。
else if (root->right == NULL) return minDepth(root->left) + 1;//沒有右孩子,只有左孩子的情況。
else return 1 + min(minDepth(root->left), minDepth(root->right));//正常的情況
}
};
2、非遞迴的方法
//層次遍歷,先增加push,後刪除pop.每遍歷一層deepth增加1
class Solution {
public:
int run(TreeNode *root)
{
queue<TreeNode*> q;
if(root==NULL) return 0;
q.push(root);
int deepth=0;
while(!q.empty())//構成一個迴圈
{
int len=q.size();
deepth++;
while(len--)//內迴圈用來刪除父節點,增加子節點
{
TreeNode *tmp=q.front();
q.pop();
if(tmp->left!=NULL) q.push(tmp->left);
if(tmp->right!=NULL) q.push(tmp->right);
if(tmp->right==NULL && tmp->left==NULL) return deepth;
}
}
return deepth;
}
};
參考幾位大佬的連結如下,感謝各位大佬的部落格:
1、http://www.cnblogs.com/grandyang/p/4042168.html
2、http://www.cnblogs.com/felixfang/p/3887565.html
3、http://blog.csdn.net/fisherming/article/details/75096410(二叉樹求深度的遞迴的詳細分析,大佬關於遞迴呼叫的詳解)
4、http://blog.csdn.net/brucehb/article/details/47453415