题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
思路:可以从根节点往下遍历,每向下遍历一个节点,深度加1,通过比较左右子树的深度,获得二叉树的深度。因为需要不断比较左右深度,采用递归的方法或者迭代的方法:
方法一:(主要是参考了剑指offer,感觉自己对递归的理解还是不深刻)
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == NULL)
return NULL;
int nLeft = TreeDepth(pRoot->left);
int nRight = TreeDepth(pRoot->right);
return (nLeft>nRight) ? (nLeft+1) : (nRight+1);
}
};
方法二:也是递归,跟上面基本一致,只不过是在讨论区看到的大神写的最简洁的代码
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == NULL) return 0;
return max(TreeDepth(pRoot->left)+1, TreeDepth(pRoot->right)+1);
}
};
方法三:迭代,层次遍历思想。一次处理一层的数据。(掌握层次遍历的思想!感觉很多题目都可以用层次遍历实现!!!)
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == NULL) 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;
}
};