首页 > 代码库 > Balanced Binary Tree
Balanced Binary Tree
Note:
a balaced tree needs to be balaced all the time. So it is important remember the status of each subtree. If it is not balaced in the middle, the full tree is not balaced. For example, this tree is not balaced: {1,2,3,4,#,5,6,7,8,9,10,11,12}
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /** * @param root: The root of binary tree. * @return: True if this Binary tree is Balanced, or false. */ private class ResultType { public int depth; public boolean isBalanced; public ResultType(int depth, boolean isBalanced) { this.depth = depth; this.isBalanced = isBalanced; } } public boolean isBalanced(TreeNode root) { // write your code here if (root == null) { return true; } return helper(root).isBalanced; } private ResultType helper(TreeNode root) { if (root == null) { return new ResultType(0, true); } ResultType left = helper(root.left); ResultType right = helper(root.right); if (Math.abs(left.depth - right.depth) <= 1 && left.isBalanced && right.isBalanced) { return new ResultType(Math.max(left.depth, right.depth) + 1, true); } else { //System.out.println(root.val); return new ResultType(Math.max(left.depth, right.depth) + 1, false); } } }
Balanced Binary Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。