LeetCode 110 Balanced Binary Tree

来源:互联网 发布:qt ros 显示界面编程 编辑:程序博客网 时间:2024/05/17 03:57

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.

本来想在一个方法里搞定,可是脑袋打不过来弯弯儿,必须调用求树的高度的方法。

如果有一个方法搞定的答案,欢迎留言。

public boolean isBalanced(TreeNode root) {return depth(root) >= 0;}public int depth(TreeNode root) {if (root == null) return 0;int highL = depth(root.left);int highR = depth(root.right);if (Math.abs(highL - highR) > 1 || highL < 0 || highR < 0) return -1;return Math.max(highL, highR) + 1;}


0 0
原创粉丝点击