二叉树的深度
OJ地址:二叉树的深度
方法一:递归
void TreeDepthHelper(TreeNode *pRoot, int curr, int &max){
if(pRoot == nullptr){
if(max < curr){
max = curr;
}
return;
}
TreeDepthHelper(pRoot->left, curr+1, max);
TreeDepthHelper(pRoot->right, curr+1, max);
}
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == nullptr){
return 0;
}
int depth = 0;
int max = 0;
TreeDepthHelper(pRoot, depth, max);
return max;
}
方法一:分治法
分治法简介:求一个规模为n的问题,先求左边规模大约为n/2的问题,再求右边规模大约为n/2的问题,然后合并左边,右边的解,从而求得最终解。具体可参考归并排序。
步骤:
求 pro(left, rigth) -> int
先求pro(left, (left+right)/2) -> lval
再求pro((left+right)/2 + 1, right) -> rval
merge(lval, rval) -> result
这里以本题为具体例子:
函数是求二叉树的最大深度,我们不必管函数具体是怎么实现的。
所以最终结果为 max( 头结点左子树的最大深度, 头结点右子树的最大深度)+1
求TreeDepth(TreeNode* pRoot)->int
先求 TreeDepth(pRoot->left) ->lval
再求TreeDepth(pRoot->right) ->rval
return max(lval, rval) + 1
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == nullptr)
return 0;
int lval, rval;
lval = rval = 0;
if(pRoot->left)
lval = TreeDepth(pRoot->left);
if(pRoot->right)
rval = TreeDepth(pRoot->right);
return max(lval, rval) + 1;
}
时间复杂度:O(n)
空间复杂度:O(n),当退化到链表时
方法二:层次遍历
求最大深度,可用队列。因为要满足先进先出的特性。
- 初始化:一个队列queue<TreeNode*> q, 将root节点入队列q
- 如果队列不空,做如下操作:
(1) 弹出队列头,保存为node,将node的左右非空孩子加入队列
(2) 做2,3步骤,直到队列为空
int TreeDepth(TreeNode* pRoot)
{
if(pRoot == nullptr)
return 0;
queue<TreeNode *> q;
q.push(pRoot);
int depth = 0;
while(!q.empty())
{
int size = q.size();
while(size--)
{
TreeNode *node = q.front();
q.pop();
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
++depth;
}
return depth;
}