}privateintgetDepth(TreeNode tree,intcurrentDepth){if(tree ==null){returncurrentDepth; }returnMath.max(getDepth(tree.left, currentDepth+1), getDepth(tree.right, currentDepth+1)); } } 写了一个getDepth()函数,访问每个节点都要调用一次这个函数。这个Solution也通过了leetcode的验证程序,但是后来想...
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 ofeverynode never differ by more than 1. Example 1: Given the following tree[3,9,20,null,null,15,7]: 3 /...
a binary tree in which the left and right subtrees of every node differ in height by no more than 1. 英文版地址 leetcode.com/problems/b 中文版描述 给定一个二叉树,判断它是否是高度平衡的二叉树。本题中,一棵高度平衡二叉树定义为:一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 ...
* 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) { return deepth(root) != -1; } private int deepth(TreeNode root) ...
LeetCode之“树”:Balanced Binary Tree 题目链接 题目要求: 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 ofeverynode never differ by more than 1....
My code: /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicbooleanisBalanced(TreeNoderoot){if(root==null)returntrue;returnhelper(root)==-1?false:tru...
Given a binary tree, determine if it is height-balanced. a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 判断一个二叉树是否为平衡二叉树 关键: 1 平衡二叉树的每一个节点的子数深度相差小于1 ...
LeetCode 110 Balanced Binary Tree === 方法一: 平衡二叉树的判定,一般来说可以在TreeNode数据结构中增加一个depth表示以该节点为根节点的子树的深度,从而利用左右儿子节点子树深度的差值做判断。 注意这里的depth是子树的深度,而不是节点的深度,这两者是相反的。 这里由于无法修改数据结构,在每次判断子树深度时都...
Python3 Code: class Solution: def isBalanced(self, root: TreeNode) -> bool: def dfs(node): if not node: return 0 l = dfs(node.left) r = dfs(node.right) return max(l, r) + 1 if not root: return True if abs(dfs(root.left) - dfs(root.right)) > 1: return False return ...
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofeverynode never differ by more than 1 参数传递法: bool isBalanced(TreeNode *root) { if(!root) return true;