코린이의 소소한 공부노트

[LeetCode/Easy] 897. Increasing Order Search Tree 본문

코딩테스트 풀이/JAVA

[LeetCode/Easy] 897. Increasing Order Search Tree

무지맘 2023. 6. 5. 23:32

1. Input

1) TreeNode root

 

2. Output

1) rootinorder로 읽어온 후 모든 노드가 오른쪽 자식만 갖게 재배열한 결과를 반환

 

3. Constraint

1) 노드 수의 범위는 [1, 100]이다.

2) 0 <= Node.val <= 1000

 

4. Example

Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9] -> Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]

 

5. Code

1) 첫 코드(2023/06/05)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode increasingBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        ArrayList<Integer> list = new ArrayList<>();
        TreeNode c = root;
        while(!stack.empty() || c!=null){
            if(c!=null){
                stack.push(c);
                c = c.left;
            } else{
                c = stack.pop();
                list.add(c.val);
                c = c.right;
            }
        }
        TreeNode ans = new TreeNode(list.get(0));
        c = ans;
        for(int i=1 ; i<list.size() ; i++){
            c.right = new TreeNode(list.get(i));
            c = c.right;
        }
        return ans;
    }
}

- 12%, 67%