用了下recursion,很快就写出来了,值得一提的是,自从上班之后越来越懒了,看了下现在写题进度,已经大不如以前了,每天上班八小时之后回到家什么都不想干。为了去google必须挺住啊。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode sortedArrayToBST(int[] num) {
return helper(num, 0, num.length-1);
}
public TreeNode helper(int[] num, int start, int end){
if(end < start) return null;
int mid = (start + end)/2;
TreeNode temp = new TreeNode(num[mid]);
temp.left = helper(num, start, mid-1);
temp.right = helper(num, mid+1, end);
return temp;
}
}
Wednesday, December 18, 2013
Thursday, December 12, 2013
Balanced Binary Tree LeetCode
简单题,如果时间复杂度为n方,这样每个节点都要算左右高度,然后判断是否差别大于1.
这样有些浪费时间,但是代码非常容易写出。如下:
/**
* Definition for binary tree
* 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;
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
if(Math.abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int getHeight(TreeNode root){
if(root == null) return 0;
return Math.max(getHeight(root.left), getHeight(root.right))+1;
}
}
如果想要O(n),必须在算高度的时候做些手脚,就判断是否差别大于1. 差别大于1就返回-1,差别小于等于1就返回高度,继续判断向上判断下一个Node。
public class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
public int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
if(left == -1) return -1;
int right = height(root.right);
if(right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
return Math.max(height(root.left), height(root.right))+1;
}
}
这样有些浪费时间,但是代码非常容易写出。如下:
/**
* Definition for binary tree
* 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;
int leftHeight = getHeight(root.left);
int rightHeight = getHeight(root.right);
if(Math.abs(leftHeight - rightHeight) > 1) return false;
return isBalanced(root.left)&&isBalanced(root.right);
}
public int getHeight(TreeNode root){
if(root == null) return 0;
return Math.max(getHeight(root.left), getHeight(root.right))+1;
}
}
如果想要O(n),必须在算高度的时候做些手脚,就判断是否差别大于1. 差别大于1就返回-1,差别小于等于1就返回高度,继续判断向上判断下一个Node。
public class Solution {
public boolean isBalanced(TreeNode root) {
return height(root) != -1;
}
public int height(TreeNode root){
if(root == null) return 0;
int left = height(root.left);
if(left == -1) return -1;
int right = height(root.right);
if(right == -1) return -1;
if(Math.abs(left - right) > 1) return -1;
return Math.max(height(root.left), height(root.right))+1;
}
}
Subscribe to:
Posts (Atom)