}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 /...
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...
* Definition for binary tree * public class TreeNode{* int val; * TreeNode left; * TreeNode right; * TreeNode(int x){val = x;}*}*/publicclassSolution{publicbooleanisBalanced(TreeNoderoot){height(root);returnrun(root);}publicbooleanrun(TreeNoderoot){if(root==null)returntrue;intl=0,r...
树的深度(高度)参考LeetCode #104 Maximum Depth of Binary Tree 二叉树的最大深度 时间复杂度O(n), 空间复杂度O(n), n为树中结点数 平衡二叉搜索树 Self-balancing binary search tree-wiki 平衡二叉搜索树(英语:Balanced Binary Tree)是一种结构平衡的二叉搜索树,即叶节点高度差的绝对值不超过1,并且左右两...
代码: 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)...
Balanced Binary Tree 今天是一道题目,来自LeetCode,难度为Easy,Acceptance为32.8%。 题目如下 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 ...
Solution1: 1/**2* Definition for binary tree3* public class TreeNode {4* int val;5* TreeNode left;6* TreeNode right;7* TreeNode(int x) { val = x; }8* }9*/10publicclassSolution{11publicbooleanisBalanced(TreeNoderoot){12//Start typing your Java solution below13//DO NOT write ma...
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right (right) {} * }; */ classSolution{ public: boolisBalanced(TreeNode*root) { ...
* 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) ...