输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。提示:
节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
我们可以采用深度优先遍历的方法,如果当前结点为nullptr就返回0,如果不是的话,就返回左子树和右子树中更深的那一棵树的深度。
- /**
- * 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 maxDepth(TreeNode* root) {
- if(root==nullptr)
- {
- return 0;
- }
- //返回左子树和右子树中更深的那一棵树的深度,同时不要忘了需要+1,因为我们当前层也是一层深度
- return max(maxDepth(root->left),maxDepth(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:
- int maxDepth(TreeNode* root) {
- if(root==nullptr)
- {
- return 0;
- }
- queue
record; - record.push(root);
- int result=0;
- while(record.empty()!=true)
- {
- //记录当前层的元素个数
- int size=record.size();
- //遍历当前层的所有元素,并且将当前层的元素的左右子树压入栈中
- while(size--)
- {
- TreeNode* tmp=record.front();
- record.pop();
- if(tmp->left)
- {
- record.push(tmp->left);
- }
- if(tmp->right)
- {
- record.push(tmp->right);
- }
- }
- //遍历完成一层,让我们的层数++
- result++;
- }
- return result;
- }
- };
可以看到广度优先遍历在内存消耗上比深度优先遍历大得多,因为我们开辟了一个队列。并且在运行时间上也没有太大的提升。所以建议采用深度优先遍历的策略