4.1

来源:互联网 发布:python文件编码转换 编辑:程序博客网 时间:2024/05/22 07:59

Topic:Implement a function to check if a binary tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that the heights of the two subtrees of any node never differ by more than one.

// 关键:空树的高度为0,有一个结点高度为1;;只有一个结点,其深度为0.高度是深度+1.

// 方法1For each node, compute the heights of each subtree, judge whether it is balanced. Time: O(n2), because on each node, we recurse through its entire subtree, this means height() is called repeatedly on the same nodes for n times.因为要递归n次,每一次递归都要用O(n)的时间来求高度,进而判断,所以时间复杂度为O(n2)

// 方法2求高度,发现不平衡了,跳出,没必要求后面的高度。当高度求出来的时候,平不平衡就求出来了。求高度只要顺次向下就行,O(n). Just change a little bit, check whether the subtree is balanced, if yes, continue, if no, return false. Time: O(n), calculate the height in the same recursion, instead of calling it again and again.

public class TreeNode {public int data;      public TreeNode left;    public TreeNode right; public TreeNode parent;public TreeNode(int data) {this.data = data;}public void setLeftChild(TreeNode left) {this.left = left;if (left != null) {left.parent = this;//设了left,同时相应的要设parent}}public void setRightChild(TreeNode right) {this.right = right;if (right != null) {right.parent = this;}}public static int height1(TreeNode root) {//有意思if(root==null){return 0;}return 1 + Math.max(height1(root.left), height1(root.right));//这个1是算上这个结点本身}public static boolean isBalanced1(TreeNode root){//从根结点开始递归,每一个子节点都要balance, 判断的标准是高度差不大于1if (root == null) {return true;}int heightDiff =height1(root.left)-height1(root.right);if(Math.abs(heightDiff)>1){return false;}else return isBalanced1(root.left)&&isBalanced1(root.right);}public static int height2(TreeNode root){// calculate the height in the same recursionif(root==null){return 0;}int leftHeight = height2(root.left);if (leftHeight == -1) {return -1;}int rightHeight = height2(root.right);if (rightHeight == -1) {return -1;}int heightDiff = leftHeight - rightHeight;if (Math.abs(heightDiff) > 1) {return -1;//发现子树不平衡了,立马返回false}else return Math.max(leftHeight, rightHeight) + 1;}public static boolean isBalanced2(TreeNode root){//height()和isBalance()方法分开写的原因是root==null时,需要返回0和nullif(height2(root)==-1){return false;}else return true;}public static void main(String[] args) {TreeNode root = null;System.out.println("empty tree: " + isBalanced2(root));TreeNode root1 = new TreeNode(0);root1.setLeftChild(new TreeNode(1));System.out.println("single left child tree: "+ isBalanced2(root1));root1.left.setLeftChild(new TreeNode(2));/** * --------root * ----left1 * left2 *  *  */System.out.println("two left child tree: " + isBalanced2(root1));root1.setRightChild(new TreeNode(3));/** * --------root * ----left1----right * left2 *  *  */System.out.println("add right to root: " + isBalanced2(root1));}}
//结果empty tree: truesingle left child tree: truetwo left child tree: falseadd right to root: true


原创粉丝点击