1. Convert Sorted Array to Binary Search Tree
题目: Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
要求, BST是平衡的!
思路: 以为是排好序的数组,所以相当于in-order的逆实现.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * careercup 4.3 * O(n) **/ public TreeNode sortedArrayToBST(int[] num) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. return createMinimalBST(num, 0, num.length-1); } private TreeNode createMinimalBST(int[] num, int left, int right){ if(left > right) return null; int mid = left + (right-left)/2; TreeNode leftChild = createMinimalBST(num, left, mid-1); TreeNode root = new TreeNode(num[mid]); root.left = leftChild; root.right = createMinimalBST(num, mid+1, right); return root; } }
同样思路, 只是要注意, Java中是传引用,不可以改变head, 例如像C++那样给head附上新的地址;
变通的方法是, 改变head的内容.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; next = null; } * } */ /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { /** * careercup 4.3 similar * O(N) * */ public TreeNode sortedListToBST(ListNode head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == null) return null; ListNode cur = head; return buildBST(cur, 0, listLength(head)-1); } private TreeNode buildBST(ListNode head, int start, int end){ if(start > end) return null; int mid = start + (end-start)/2; TreeNode left = buildBST(head, start, mid-1); TreeNode root = new TreeNode(head.val); root.left = left; if(head.next != null){ head.val = head.next.val; head.next = head.next.next; } root.right = buildBST(head, mid+1, end); return root; } private int listLength(ListNode head){ if(head == null) return 0; int len = 1; ListNode cur = head; while(cur.next != null){ len++; cur = cur.next; } return len; } }
-- Mirror a Tree
public void mirrorTree(TreeNode root){ if(root == null) return; mirrorTree(root.left); mirrorTree(root.right); TreeNode temp = root.left; root.left = root.right; root.right = temp; }