代码拉取完成,页面将自动刷新
同步操作将从 doocs/leetcode 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.
Example 1:
Given tree [3,9,20,null,null,15,7] 3 / \ 9 20 / \ 15 7 return true.
Example 2:
Given [1,2,2,3,3,null,null,4,4] 1 / \ 2 2 / \ 3 3 / \ 4 4 return false.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
l, r = self._height(root.left), self._height(root.right)
return abs(l - r) < 2 and self.isBalanced(root.left) and self.isBalanced(root.right)
def _height(self, node):
if not node:
return 0
return 1 + max(self._height(node.left), self._height(node.right))
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null) {
return true;
}
int l = height(root.left), r = height(root.right);
return Math.abs(l - r) < 2 && isBalanced(root.left) && isBalanced(root.right);
}
private int height(TreeNode node) {
if (node == null) {
return 0;
}
return 1 + Math.max(height(node.left), height(node.right));
}
}
Bottom-up recursion
func isBalanced(root *TreeNode) bool {
return depth(root) >= 0
}
func depth(root *TreeNode) int {
if root == nil {
return 0
}
left := depth(root.Left)
right := depth(root.Right)
if left == -1 || right == -1 || abs(left-right) > 1 {
return -1
}
return max(left, right) + 1
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。