Post

[LeetCode 144] Binary Tree Preorder Traversal

LeetCode 144 (Java)
[Binary Tree Preorder Traversal] 문제 풀이

[LeetCode 144] Binary Tree Preorder Traversal

문제 바로가기


Description


Given the root of a binary tree, return the preorder traversal of its nodes’ values.


Example 1


  • Input: root = [1,null,2,3]
  • Output: [1,2,3]
  • Explanation:


Example 2


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


Example 3


  • Input: root = []
  • Output: []


Example 4


  • Input: root = [1]
  • Output: [1]


Constraints


  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100







Code


내 제출


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
 * 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 {
    private List<Integer> ans = new ArrayList<>();

    public List<Integer> preorderTraversal(TreeNode root) {
        dfs(root);
        return ans;
    }

    private void dfs(TreeNode root) {
        if (root == null) {
            return;
        }
        ans.add(root.val);
        dfs(root.left);
        dfs(root.right);
    }
}


RuntimeMemory
0 ms41.7 MB


다른 풀이


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 /**
 * 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 List<Integer> preorderTraversal(TreeNode root) {
        ArrayList<Integer> ans = new ArrayList<>();
        if (root == null) return ans;
        Stack<TreeNode> sc = new Stack<>();
        sc.push(root);
        while(sc.size() > 0) {
            TreeNode top = sc.pop();
            ans.add(top.val);
            if(top.right != null) sc.push(top.right);
            if(top.left != null) sc.push(top.left);
        }
        return ans;
    }
}


Reference


This post is licensed under CC BY 4.0 by the author.