LeetCode110 Blanced Binary Tree Java 题解

来源:互联网 发布:耳鸣 知乎 编辑:程序博客网 时间:2024/06/06 15:34

题目:

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.


题解:

判断一颗二叉树是不是平衡二叉树  ,平衡二叉树是每个节点都满足指左右子树的高度差小于1

我们通过计算每一个节点的左右高度差  一旦发现有不满足的节点就将返回值置为-1   这两句代码if(left==-1) return -1;
if(right==-1) return -1保证只要出现一个高度差为-1的最终返回结果必然为-1,也就是说最终可以根据返回值是不是-1判断是不是平衡二叉树


代码:

public static boolean isBalanced(TreeNode root) {if(treeHight(root)==-1)return false;else return true;            }public static int treeHight(TreeNode root){if(root==null)return 0;else {int left=treeHight(root.left);int right=treeHight(root.right);if(left==-1) return -1;if(right==-1) return -1;if(Math.abs(left-right)>1)return -1;else {return 1+Math.max(treeHight(root.left), treeHight(root.right));}}}


0 0
原创粉丝点击