题目:
110. Balanced Binary Tree
Easy
1229108FavoriteShare
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
这道题,在还没看答案之前也没想到什么好方法,看了答案以后就觉得很妙了。其实它的本质就是一个求树高的问题,只是对每个节点都求一次,一共有两种不同的实现方法。
第一种实现方法是“从上到下”的遍历,每遍历一个节点就计算它的左右子树高度差是否大于1,判断每一个节点是否符合条件,求树高就直接可以用之前做过的maximum depth函数,总体实现起来非常顺利。
第二种实现方法是“从下到上”的遍历,和前面一种一样,都是采用了求树高的方法,但为什么说是从下到上,是因为它每遇到一个节点,都会先向下DFS到最深的节点,然后慢慢向上递归求树高,当左右两边树高差距超过1时就返回-1(作为不平衡的标志),这也相当于对所有的节点进行一次遍历就可以完成。
所以,总结一下,两种方法的本质其实是一样的,只是在不同的地方比较节点的两棵子树的高度(第一种:从上到下遍历时;第二种:从下往上遍历时)(感觉我不能很好地把这个思想表达出来,捉急)。
但是第一种方法,对每个节点求树高的平均复杂度是O(logN),最坏复杂度是O(N^2),遍历一遍所有节点的复杂度是O(N),总体平均复杂度是O(NlogN);而第二种方法只需要对每个节点进行一次遍历,平均复杂度是O(N)。
以下是代码实现,第一种方法时间16ms,89.46%,空间17.6M,10.60%:
/*
* @lc app=leetcode id=110 lang=cpp
*
* [110] Balanced Binary Tree
*/
/**
* 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 depth(TreeNode* root) {
if (!root) {
return 0;
}
return max(depth(root->left), depth(root->right)) + 1;
}
bool isBalanced(TreeNode* root) {
if (!root) {
return true;
}
int right_depth = depth(root->right);
int left_depth = depth(root->left);
if (abs(right_depth - left_depth) > 1) {
return false;
}
return isBalanced(root->right) && isBalanced(root->left);
}
};
2020.10.21 Java
刚开始想偏了,试图直接找最优解没有想着直接用最简单的。看了笔记还是直接写了这种做法,但是注意edge case:
Runtime: 1 ms, faster than 53.10% of Java online submissions for Balanced Binary Tree.
Memory Usage: 39.1 MB, less than 15.75% of Java online submissions for Balanced Binary Tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (Math.abs(height(root.left) - height(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode root) {
if (root == null) {
return 0;
}
int left = height(root.left) + 1;
int right = height(root.right) + 1;
return Math.max(left, right);
}
}
2023.1.4
勉勉强强还是差一点写出来,哎……
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
if (Math.abs(height(root.left) - height(root.right)) > 1) {
return false;
}
return isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode root) {
if (root == null) {
return 0;
}
int result = 1 + Math.max(height(root.left), height(root.right));
return result;
}
}
第二种方法,时间12ms,96.10%,空间17.6M,41.21%:
/*
* @lc app=leetcode id=110 lang=cpp
*
* [110] Balanced Binary Tree
*/
/**
* 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 depth(TreeNode* root) {
if (!root) {
return 0;
}
int right_depth = depth(root->right);
if (right_depth == -1) {
return -1;
}
int left_depth = depth(root->left);
if (left_depth == -1) {
return -1;
}
if (abs(right_depth - left_depth) > 1) {
return -1;
}
return max(left_depth, right_depth) + 1;
}
bool isBalanced(TreeNode* root) {
return depth(root) != -1;
}
};
2020.10.21 Java
这种方法也没完全写出来,首先是要考虑怎样表示这是个unbalanced的——可以直接把height return成-1表示。另外还有一点小坑在于我习惯性在求出left right的时候马上+1,那么在判断左右可能为-1的时候就要用0而不是-1了,为了防止confusing就还是在最后的时候才+1了。
Runtime: 0 ms, faster than 100.00% of Java online submissions for Balanced Binary Tree.
Memory Usage: 38.9 MB, less than 15.75% of Java online submissions for Balanced Binary Tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode root) {
if (root == null) {
return 0;
}
int left = height(root.left); // should add 1 at the end
int right = height(root.right); // should add 1 at the end
if (left == -1 || right == -1 || Math.abs(left - right) > 1) {
return -1;
}
return Math.max(left, right) + 1;
}
}
2023.1.4
依旧不会写这种方法。我觉得这个方法更像是提早return,为此还特意print出来看了一眼(实在是懒得自己画一遍了)。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
private int height(TreeNode root) {
if (root == null) {
return 0;
}
int left = height(root.left);
if (left == -1) {
System.out.println("left = -1");
return -1;
}
int right = height(root.right);
if (right == -1) {
System.out.println("right = -1");
return -1;
}
if (Math.abs(left - right) > 1) {
System.out.println("abs > 1");
return -1;
}
System.out.println(root.val + ": " + (Math.max(left, right) + 1));
return Math.max(left, right) + 1;
}
}
比如下面这棵树print出来是这样的:[1,2,2,3,3,null,null,4,4,null,null,null,null,null,5]
4: 1
5: 1
4: 2
3: 3
3: 1
abs > 1
left = -1
2023.1.4
然后又知道了还有iterative的写法,啊,脑袋空空。这题要用iterative做,只能用post order,因为得先得到它子节点的高度才能得到它自己的高度。post order的迭代写法还没复习到,这次相当于从头学起了。preorder的时候是直接在while里先stack.pop了,这里只能是stack.peek。然后因为postorder里会出现先算完子节点然后回去root的情况,但是因为在if里又要push left和right,所以得用一个数据结构来存放是否遍历过当前节点,所以if的条件有两个:!= null和!contains。同样的,几个if也是if-else的逻辑关系,不像是preorder一样不需要else。只有用了else才能一次全部往里push一个方向的。嗯,暂时就学到了这些,等下次做postorder的时候再仔细研究一下。
代码(含print):
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
Deque<TreeNode> stack = new ArrayDeque<>();
Map<TreeNode, Integer> map = new HashMap<>(); // node to the height of subtree rooted from the node
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.peek();
if (node.left != null && !map.containsKey(node.left)) {
stack.push(node.left);
} else if (node.right != null && !map.containsKey(node.right)) {
stack.push(node.right);
} else {
node = stack.remove();
int leftHeight = map.getOrDefault(node.left, 0);
int rightHeight = map.getOrDefault(node.right, 0);
System.out.println(node.val + ": " + leftHeight + ", " + rightHeight);
if (Math.abs(leftHeight - rightHeight) > 1) {
System.out.println("false");
return false;
}
map.put(node, Math.max(leftHeight, rightHeight) + 1);
System.out.println(node.val + ": " + (Math.max(leftHeight, rightHeight) + 1));
}
}
return true;
}
}
栗子: