題目描述
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。
分析:可以用遞歸,也可以用非遞歸,有兩種想法,一種是深度優先遍歷,用遞歸就可以,還有一種是層序遍歷,用隊列實現。
代碼:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int res=0,maxres=0;
int TreeDepth(TreeNode* pRoot)
{
if(pRoot==NULL)
return 0;
res++;
TreeDepth(pRoot->left);
TreeDepth(pRoot->right);
if(res>maxres)
maxres=res;
res--;
return maxres;
}
};
其實遞歸的代碼有比這個還有簡單的多的版本:
鏈接:https://www.nowcoder.com/questionTerminal/435fb86331474282a3499955f0a41e8b
來源:牛客網
class
Solution { public : int
TreeDepth(TreeNode* pRoot){ if (!pRoot)
return 0 ;
return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right)); } }; |
來源:牛客網
// 遞歸遍歷,僅僅一行
class
Solution {
public
:
int
TreeDepth(TreeNode* pRoot){
return
pRoot ? max(TreeDepth(pRoot->left),TreeDepth(pRoot->right))+1 :0;
}
};
//迭代版本
class
Solution {
public
:
int
TreeDepth(TreeNode* pRoot) {
if
(!pRoot)
return
0;
queue<TreeNode*> que;
que.push(pRoot);
int
depth=0;
while
(!que.empty()) {
int
size=que.size();
depth++;
for
(
int
i=0;i<size;i++) {
//一次處理一層的數據
TreeNode *node=que.front();
que.pop();
if
(node->left) que.push(node->left);
if
(node->right) que.push(node->right);
}
}
return
depth;
}
};