二叉树的深度

三种方法:递归,深搜,宽搜;

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    int count=0,maxdepth=0;
    int TreeDepth(TreeNode* pRoot)
    {
        //递归
        /*if(pRoot==NULL){
            return 0;
        }
        if(pRoot->left==NULL&&pRoot->right==NULL)
            return 1;
        int count_left=TreeDepth(pRoot->left);
        int count_right=TreeDepth(pRoot->right);

        return count_left>count_right?(count_left+1):(count_right+1);
        //宽度搜索
        if(pRoot==NULL){
            return 0;
        }
        queue<TreeNode*> q;
        q.push(pRoot);
        int level=0;
        while(!q.empty()){
            int size=q.size();
            level++;
            while(size--){
                TreeNode* p=q.front();
                q.pop();
                if(p->left) q.push(p->left);
                if(p->right) q.push(p->right);

            }
        }
        return level;*/
        //深度搜索
        if(pRoot==NULL){
            return 0;
        }
        stack<TreeNode*> s;
        s.push(pRoot);
        int level=1,max=0;
        while(!s.empty()){
            TreeNode* p=s.top();
            s.pop();

            if(p->left==NULL&&p->right==NULL) {
                if(level>max)
                    max=level;
                level--;
            }
            else{
                if(p->left!=NULL) s.push(p->left);
                if(p->right!=NULL) s.push(p->right);
                level++;
            }


        }
        return max;


    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值