1988coder

654. Maximum Binary Tree

Feb 26th, 2019
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/maximum-binary-tree/
  3. import java.util.Stack;
  4.  
  5. // Definition for a binary tree node.
  6. class TreeNode {
  7.     int val;
  8.     TreeNode left;
  9.     TreeNode right;
  10.  
  11.     TreeNode(int x) {
  12.         val = x;
  13.     }
  14. }
  15.  
  16. /**
  17.  * Refer :
  18.  * https://leetcode.com/problems/maximum-binary-tree/discuss/106156/Java-worst-case-O(N)-solution/143674
  19.  *
  20.  * Time Complexity: O(N). Each TreeNode will be created once, and will be put
  21.  * into the stack and move out of the stack once for worst case. So the time
  22.  * complexity is O(N).
  23.  *
  24.  * Space Complexity: O(N). In worst case, if the array is in descending order.
  25.  */
  26. class Solution {
  27.     public TreeNode constructMaximumBinaryTree(int[] nums) {
  28.         if (nums == null || nums.length == 0) {
  29.             return null;
  30.         }
  31.  
  32.         Stack<TreeNode> stack = new Stack<>();
  33.  
  34.         for (int n : nums) {
  35.             TreeNode cur = new TreeNode(n);
  36.  
  37.             while (!stack.isEmpty() && stack.peek().val < n) {
  38.                 cur.left = stack.pop();
  39.             }
  40.  
  41.             if (!stack.isEmpty()) {
  42.                 stack.peek().right = cur;
  43.             }
  44.  
  45.             stack.push(cur);
  46.         }
  47.  
  48.         return stack.isEmpty() ? null : stack.get(0);
  49.     }
  50. }
Add Comment
Please, Sign In to add comment