该算法的思路是基于Solution #1的一种改进,把每个节点的height信息和isBalanced信息融合到一起个变量中: 如果该变量>=0,那么该节点是balanced并且该变量就是节点的height; 如果该变量<0,那么该节点是unbalanced,但同时我们失去了它的height信息。 publicclassCheckTreeBalanced2 {publicintcheckHeight(TreeNode root){if...
* Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public boolean isBalanced(TreeNode root) { if(root == null){ return true; } if(root.left==null && root.rig...
Balanced Binary Tree Description 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 ...
平衡二叉树 - 力扣(LeetCode)leetcode-cn.com/problems/balanced-binary-tree/ 题目描述 给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高度平衡二叉树定义为: 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过1。 示例1: 给定二叉树 [3,9,20,null,null,15,7] 3 / \ 9 ...
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. 自己的答案 理解什么是二叉平衡树很重要,按照定义用递归的方法可以较容易写出答案,如下: class Solution { public boolean isBalanced(Tree...
* 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; ...
Balanced Binary Tree 题目 https://leetcode.com/problems/balanced-binary-tree/description/ 判断一棵二叉树是否是平衡二叉树。 平衡二叉树指的是,两棵子树的任一节点的深度相差不超过1. 思路及解法 首先写一个函数用来得到每一个子树的深度,然后递归调用原函数,判断两棵子树的深度差... 查看原文 LeetCode-...
1/**2* Definition for a binary tree node.3* struct TreeNode {4* int val;5* TreeNode *left;6* TreeNode *right;7* TreeNode(int x) : val(x), left(NULL), right(NULL) {}8* };9*/10classSolution {11public:12boolisBalanced(TreeNode*root) {13returnisBalancedSub(root);14}1516bool...
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]: ...
Can you solve this real interview question? Balanced Binary Tree - Given a binary tree, determine if it is height-balanced. Example 1: [https://assets.leetcode.com/uploads/2020/10/06/balance_1.jpg] Input: root = [3,9,20,null,null,15,7] Output: tru