classSolution2 {public:boolisBalanced(TreeNode*root) {if(root==NULL){returntrue; }intheight=getheight(root);if(height==-1){returnfalse; }returntrue; }intgetheight(TreeNode *root){if(root==NULL){return0; }intlleft=getheight(root->left);inttrigth=getheight(root->right);if(lleft==-1...
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 Solution::isBalanced(...
leetcode -day18 Balanced Binary Tree 测试源码: //测试派生类的构造函数的调用顺序何时调用 //Fedora20 gcc version=4.8.2 #include <iostream> using namespace std; class base { public: base() { cout<<"base created!"<<endl; } ~base() { cout<<"base destroyed!"<<
package leetcode /** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func isBalanced(root *TreeNode) bool { if root == nil { return true } leftHight := depth(root.Left) rightHight := depth(root.Right) retur...
left), getHeight(treeNode.right)) + 1; } } 官方版 方法一:自顶向下的递归 class Solution { public boolean isBalanced(TreeNode root) { if (root == null) { return true; } else { return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced...
树的深度(高度)参考LeetCode #104 Maximum Depth of Binary Tree 二叉树的最大深度 时间复杂度O(n), 空间复杂度O(n), n为树中结点数 平衡二叉搜索树 Self-balancing binary search tree-wiki 平衡二叉搜索树(英语:Balanced Binary Tree)是一种结构平衡的二叉搜索树,即叶节点高度差的绝对值不超过1,并且左右两...
LeetCode 110. 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. ...
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. 代码: classSolution{//c++public:intgetHigh(TreeNode*root,bool&isBalanc){if(root->left==NULL&&root->right==NULL)return1;intlmin...
* Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { ...
代码: boolSolution::isBalanced(TreeNode*root){if(root==NULL)returntrue;if(abs(treeHeight(root->left)-treeHeight(root->right))>1)returnfalse;returnisBalanced(root->left)&&isBalanced(root->right);}intmax(inta,intb){returna>b?a:b;}intSolution::treeHeight(TreeNode*root){if(root==NULL)...