剑指offer-二叉树的深度(C++ 递归+层次遍历)

二叉树的深度

输入一棵二叉树,求该树的深度。从根节点到叶节点依次经过的结点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

题解:
针对此题,有多种解法,下面介绍其中两种。
1)递归法:
通过递归,来不断计算最长路径,代码如下:

/*
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){
        int depth;
        if(!pRoot) return 0;
        int left=TreeDepth(pRoot->left);
        int right=TreeDepth(pRoot->right);
        depth=max(left,right);
        return depth+1;
        }
}

2)层次遍历法
将每层的节点数存入队列中。即一层一层的将每层的节点数都送入队列,每输出一层节点,就送入该层的下一层节点。最后得到节点数。

/*
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){
        /*int depth;
        if(!pRoot) return 0;
        int left=TreeDepth(pRoot->left);
        int right=TreeDepth(pRoot->right);
        depth=max(left,right);
        return depth+1;*/
        queue<TreeNode*> q1;//每层的节点
        queue<int> q2;//每层节点数量
        if(!pRoot) return 0;
        q1.push(pRoot);//存入根节点
        q2.push(1);//根节点数为1个
        int depth=0;
        while(q1.size()!=0){
            TreeNode *p;
            int temp1,temp2;
            temp1=q2.front();//获得每层的节点数量
            q2.pop();
            temp2=0;
            depth++;
            while(temp1){//输出每层的节点,并送入该层的子节点
                p=q1.front();
                q1.pop();
                if(p->left){
                    q1.push(p->left);
                    temp2++;}
                if(p->right) {
                    q1.push(p->right);
                    temp2++;}
                temp1--;//输出完该层所有节点,压入该层的节点数
                if(!temp1) 
                    q2.push(temp2);
            }
        }
        return depth;
    }
};
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值