LeetCode - 144. Binary Tree PreOrder Traversal(stack, tree, DFS, Binary Tree)

YAMAMAMO·2023년 1월 4일
0

LeetCode

목록 보기
97/100

문제

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

https://assets.leetcode.com/uploads/2020/09/15/inorder_1.jpg

Example 1:

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

Example 2:

Input: root = []
Output: []

Example 3:

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

풀이

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        preOrder(root, res);
        return res;
    }

    public void preOrder(TreeNode root, List<Integer> list){
        if(root == null) return;
        list.add(root.val);
        preOrder(root.left, list);
        preOrder(root.right, list);
    }
}
profile
안드로이드 개발자

0개의 댓글