中级农民
- 积分
- 100
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2016-1-24
- 最后登录
- 1970-1-1
|
合一下楼上讨论的代码
- public class Solution {
- public TreeNode buildMinHeap(int[] arr, int start, int end) {
- if (start >= end) {
- return null;
- }
- int root = start;
- for (int i = start + 1; i < end; i++) {
- if (arr[i] < arr[root]) {
- root = i;
- }
- }
- TreeNode ret = new TreeNode(arr[root]);
- ret.left = buildMinHeap(arr, start, root);
- ret.right = buildMinHeap(arr, root + 1, end);
- return ret;
- }
- public void inorder(TreeNode root) {
- if (root != null) {
- inorder(root.left);
- System.out.print(root.val + " ");
- inorder(root.right);
- }
- }
- public boolean isMinHeap(TreeNode root, int parentVal) {
- if (root == null)
- return true;
- if (root != null && root.val < parentVal) {
- return false;
- }
- return isMinHeap(root.left, root.val) && isMinHeap(root.right, root.val);
- }
- public TreeNode addToMinHeap(TreeNode root, int val) {
- if (root.val > val) {
- TreeNode ret = new TreeNode(val);
- ret.left = root;
- return root;
- }
- //
- TreeNode p = root;
- while (p.right != null && p.right.val < val) { // break if null or greater val
- p = p.right;
- }
- TreeNode newnode = new TreeNode(val);
- newnode.left = p.right; // add to right child and make old subtree as left child
- p.right = newnode;
- return root;
- }
- public TreeNode addtoMinHeap(TreeNode root, int[] newvals) {
- TreeNode newroot = buildMinHeap(newvals, 0, newvals.length);
- return merge(root, newroot);
- }
- private TreeNode merge(TreeNode root1, TreeNode root2) {
- if (root1 == null) {
- return root2;
- }
- if (root2 == null) {
- return root1;
- }
- if (root1.val < root2.val) {
- root1.right = merge(root1.right, root2);
- return root1;
- } else {
- root2.left = merge(root1, root2.left);
- return root2;
- }
- }
- public static void main(String[] args) {
- Solution s = new Solution();
- int[] arr = new int[] {3, 2, 5, 6, 4, 1, 9, 0};
- TreeNode root = s.buildMinHeap(arr, 0, arr.length);
- s.inorder(root);
- System.out.println();
- System.out.println(s.isMinHeap(root, Integer.MIN_VALUE));
- root = s.addToMinHeap(root, 7);
- s.inorder(root);
- System.out.println();
- System.out.println(s.isMinHeap(root, Integer.MIN_VALUE));
- root = s.addtoMinHeap(root, new int[] {10, 11, 12, 13});
- s.inorder(root);
- System.out.println();
- System.out.println(s.isMinHeap(root, Integer.MIN_VALUE));
- root = s.addtoMinHeap(root, new int[] {-1, 11, -12, 13});
- s.inorder(root);
- System.out.println();
- System.out.println(s.isMinHeap(root, Integer.MIN_VALUE));
- return;
- }
- }
复制代码 |
|