AcWing 71. 二叉树的深度
原题链接
简单
作者:
GanaWeng
,
2023-09-19 20:36:06
,
所有人可见
,
阅读 62
求二叉树的深度(高度)
递归法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int treeDepth(TreeNode* root) {
if(!root) return 0;
return max(treeDepth(root->left), treeDepth(root->right)) + 1;
}
};
非递归法,利用树的层次遍历
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
queue<TreeNode*> q;
int depth;
int treeDepth(TreeNode* root) {
if(!root) return 0;
q.push(root);
while(q.size())//当队列非空时
{
int n = q.size();
while (n -- ){//将同一层元素全部出队
TreeNode* t = q.front();
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
depth ++;//每出队一层元素,深度+1
}
return depth;
}
};