首页 > 代码库 > 110. Balanced Binary Tree
110. 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 of every node never differ by more than 1.
Solution 1:
思路:首先判断root.left和root.right是否有符合条件的depth,加入辅助函数,也就是104的maxdepth,然后再递归检查左子树和右子树。
/** * Definition for a binary tree node. * 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(Math.abs(depth(root.left)-depth(root.right))<=1) { return isBalanced(root.left)&&isBalanced(root.right); } else { return false; } } public int depth(TreeNode root) { if(root==null) { return 0; } return Math.max(depth(root.left),depth(root.right))+1; } }
Solution 2:
discussion看到一种更巧妙的做法:
public boolean isBalanced(TreeNode root) { return getDepth(root) != -1;}private int getDepth(TreeNode root) { if (root != null) { int left = getDepth(root.left); int right = getDepth(root.right); return (left == -1 || right == -1 || Math.abs(left-right) > 1) ? -1 : Math.max(left, right) + 1; } return 0;}
Define a getDepth method, which will return the height of the tree, if it is balanced, otherwise, return -1.
定义的这个getDepth行使两个功能,一是记录depth如果balanced,二是记录-1如果不balanced。
定义好一个recursion的函数很重要啊!!
110. Balanced Binary Tree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。