LeetCode problem#897
Increasing Order Search Tree
Solved in 1 languageJava
Solution
52 lines
1/**
2 * Definition for a binary tree node.
3 * public class TreeNode {
4 * int val;
5 * TreeNode left;
6 * TreeNode right;
7 * TreeNode() {}
8 * TreeNode(int val) { this.val = val; }
9 * TreeNode(int val, TreeNode left, TreeNode right) {
10 * this.val = val;
11 * this.left = left;
12 * this.right = right;
13 * }
14 * }
15 */
16class Solution {
17 public TreeNode increasingBST(TreeNode root) {
18 TreeNode curr = root;
19 Stack<TreeNode> stack = new Stack<TreeNode>();
20 List<TreeNode> list = new LinkedList<TreeNode>();
21
22 while (curr != null || !stack.isEmpty()) {
23 if (curr != null) {
24 stack.push(curr);
25 curr = curr.left;
26 }
27 else {
28 curr = stack.pop();
29 list.add(curr);
30 curr = curr.right;
31 }
32 }
33
34 for (int i = 0; i < list.size(); i++) {
35 TreeNode currentNode = list.get(i);
36
37 currentNode.left = null;
38 // the following conditional is actually not even necessary if
39 // your loop condition is < list.size() - 1, since you know for
40 // sure the rightmost Node, with the highest value, will not
41 // have a right child.
42 if (i < list.size() - 1) {
43 currentNode.right = list.get(i + 1);
44 }
45 else {
46 currentNode.right = null;
47 }
48 }
49
50 return list.get(0);
51 }
52}Want a walkthrough of this Java solution?
Get a step-by-step explanation of the idea behind the code.
Problem statements belong to LeetCode and are on leetcode.com. We're not affiliated with LeetCode.