二叉树的深度

    xiaoxiao2026-10-06  1

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

    /* 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; } };
    转载请注明原文地址: https://ju.6miu.com/read-1312694.html
    最新回复(0)