题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
方法一:
递归方法
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if (!pRoot)
return 0;
int leftDepth = TreeDepth(pRoot->left);
int rightDepth = TreeDepth(pRoot->right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
};
方法二:
迭代方法,利用层次遍历的思想,last指向当前层的最右结点,每次层次遍历出队时与last指针比较,若两者相等,则深度depth加1,并让last,指向下一层的最右结点,直到遍历完成。depth的值即是二叉树的高度
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
int TreeDepth(TreeNode* pRoot)
{
if (!pRoot)
return 0;
queue<TreeNode*> nodeQueue;
nodeQueue.push(pRoot);
int first = 0;
int last = 1;
int depth = 0;
while (!nodeQueue.empty()) {
TreeNode* currentNode = nodeQueue.front();
nodeQueue.pop();
first++;
if (currentNode->left)
nodeQueue.push(currentNode->left);
if (currentNode->right)
nodeQueue.push(currentNode->right);
if (first == last) {
depth++;
last = nodeQueue.size();
first = 0;
}
}
return depth;
}
};