110. 平衡二叉树

描述

给定一个二叉树,判断它是否是高度平衡的二叉树。

本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。

示例 1:

给定二叉树 [3,9,20,null,null,15,7]

110.平衡二叉树

返回 true 。

示例 2:

给定二叉树 [1,2,2,3,3,null,null,4,4]

110.平衡二叉树1

返回 false 。

链接

110. 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)

解法

相关知识

高度和深度是相反的表示,深度是从上到下数的,而高度是从下往上数。

因为求深度可以从上到下去查 所以需要前序遍历(中左右),而高度只能从下到上去查,所以只能后序遍历(左右中)。

 二叉树的高度和深度的区别_帝轩的博客-CSDN博客

代码随想录 (programmercarl.com)

 

解法一:先序遍历 + 判断深度

 1 class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         if(root == null) return true;
 4         return Math.abs(depth(root.left)-depth(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right);
 5     }
 6     private int depth(TreeNode node) {
 7         if(node == null) return 0;
 8         return Math.max(depth(node.left),depth(node.right)) + 1;
 9     }
10 }

解法二:后序遍历 + 剪枝 (从底至顶)

 1 class Solution {
 2     public boolean isBalanced(TreeNode root) {
 3         return recur(root) != -1;
 4     }
 5     public int recur(TreeNode root) {
 6         // 1、 特例
 7         if (root == null) return 0;
 8         // 2、 左子树
 9         int left = recur(root.left);
10         if (left == -1) return -1; //剪枝
11         // 3、 右子树
12         int right = recur(root.right);
13         if ( right == -1) return -1;  //剪枝
14         // 递归 返回值
15         return Math.abs(left - right) < 2 ? Math.max(left,right) + 1 : -1;
16     }

 

题解链接

面试题55 - II. 平衡二叉树(从底至顶、从顶至底,清晰图解) - 平衡二叉树 - 力扣(LeetCode) (leetcode-cn.com)

 

posted @ 2021-11-01 19:45  DidUStudy  阅读(30)  评论(0编辑  收藏  举报