题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
利用队列的先进先出, 思想是弹出当前层, 插入下一层
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if (nullptr == pRoot)
return 0;
queue<TreeNode *> q;
int depth = 0;
q.push(pRoot);
while (!q.empty()) {
depth++;
int size = q.size();
// 由于for里面还有插入, 所以for循环结束不能直接用q.size()
//for (int i = 0; i < q.size(); i++) {
for (int i = 0; i < size; i++) { // 弹出当前层, 插入下一层
TreeNode *temp = q.front();
q.pop();
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
}
return depth;
}
};
树的遍历, 插一句It doesn't work why, it works why?
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
int rightHigh = 1;
int leftHigh = 1;
if (nullptr == pRoot) {
return 0;
}
if (nullptr != pRoot->left) {
rightHigh += TreeDepth(pRoot->left);
}
if (nullptr != pRoot->right) {
leftHigh += TreeDepth(pRoot->right);
}
return rightHigh > leftHigh ? rightHigh : leftHigh;
}
};
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/