目录
剑指 Offer 55 - I. 二叉树的深度
剑指 Offer 55 - II. 平衡二叉树
剑指 Offer 55 - I. 二叉树的深度
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7返回它的最大深度 3 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。【解法一】后续遍历递归
class Solution { public: int maxDepth(TreeNode* root) { if(root==nullptr)return 0; int left = maxDepth(root->left); int right = maxDepth(root->right); return 1+max(left, right); } };
【解法二】BFS 利用队列层序遍历结点,根据层序遍历次数即为深度;
class Solution { public: int maxDepth(TreeNode* root) { queue<TreeNode*> q; int depth = 0; if(root != nullptr)q.push(root); while(!q.empty()) { int size = q.size(); while(size>0) { TreeNode* cur = q.front(); q.pop(); if(cur->left)q.push(cur->left); if(cur->right)q.push(cur->right); size-=1; } depth+=1; } return depth; } };
剑指 Offer 55 - II. 平衡二叉树
输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7返回 true 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/ping-heng-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。【解法一】递归判断左右子树深度之差是否小于1
class Solution { public: int depth(TreeNode* root) { if(root==nullptr)return 0; int left = depth(root->left); int right = depth(root->right); return 1 + max(left, right); } bool isBalanced(TreeNode* root) { if(root==nullptr)return true; if(abs(depth(root->left)-depth(root->right)) > 1) return false; return isBalanced(root->left) && isBalanced(root->right); } };