1988coder

998. Maximum Binary Tree II

Feb 26th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. // LeetCode URL: https://leetcode.com/problems/maximum-binary-tree/
  2.  
  3. // Definition for a binary tree node.
  4. class TreeNode {
  5.     int val;
  6.     TreeNode left;
  7.     TreeNode right;
  8.  
  9.     TreeNode(int x) {
  10.         val = x;
  11.     }
  12. }
  13.  
  14. // Refer for explanation:
  15. // https://leetcode.com/problems/maximum-binary-tree-ii/discuss/242936/JavaC++Python-Recursion-and-Iteration
  16. // Always go right since new element will be inserted at the end of the list.
  17.  
  18. /**
  19.  * Recursive Solution
  20.  *
  21.  * Time Complexity: O(Length of right most path) = O(N) in worst case.
  22.  *
  23.  * Space Complexity: O(Length of right most path) = O(N) in worst case.
  24.  */
  25. class Solution1 {
  26.     public TreeNode insertIntoMaxTree(TreeNode root, int val) {
  27.         if (root == null) {
  28.             return new TreeNode(val);
  29.         }
  30.  
  31.         if (root.val < val) {
  32.             TreeNode node = new TreeNode(val);
  33.             node.left = root;
  34.             return node;
  35.         }
  36.  
  37.         root.right = insertIntoMaxTree(root.right, val);
  38.         return root;
  39.     }
  40. }
  41.  
  42. /**
  43.  * Iterative Solution
  44.  *
  45.  * Time Complexity: O(Length of right most path) = O(N) in worst case.
  46.  *
  47.  * Space Complexity: O(1)
  48.  */
  49. class Solution2 {
  50.     public TreeNode insertIntoMaxTree(TreeNode root, int val) {
  51.         TreeNode node = new TreeNode(val);
  52.         if (root == null || root.val < val) {
  53.             node.left = root;
  54.             return node;
  55.         }
  56.  
  57.         TreeNode cur = root;
  58.  
  59.         while (cur.right != null && cur.right.val > val) {
  60.             cur = cur.right;
  61.         }
  62.  
  63.         node.left = cur.right;
  64.         cur.right = node;
  65.         return root;
  66.     }
  67. }
Add Comment
Please, Sign In to add comment