本文主要是介绍leetcode110~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.
判断一棵树是否为平衡二叉树。
平衡二叉树:对于树中每一个节点来说,左右子树的高度差不能超过1.
关键:使用递归求出子树高度,然后做差比较即可。返回-1代表非平衡。
在给出本题代码之前,先附上求树高度的代码,便于理解:
public int getHeight(TreeNode root){if(root==null) return 0;int left = getHeight(root.left);int right = getHeight(root.right);return Math.max(left,right)+1;
}
只需对上面代码稍微修改一下即可:
public class IsBalanced {public boolean isBalanced(TreeNode root) {if(getHeight(root)==-1) {return false;} else {return true;}}private int getHeight(TreeNode root) {if(root==null) return 0;int left = getHeight(root.left);int right = getHeight(root.right);if(left==-1 || right==-1 || Math.abs(left-right)>1) {return -1;}return Math.max(left, right)+1;}
}
这篇关于leetcode110~Balanced Binary Tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!