본문 바로가기
Leetcode

Leetcode 144. Binary Tree Preorder Traversal 54.3% Medium

by tiit 2020. 4. 3.
반응형

스터디 알고리즘 문제1 Stack 정답률 54.3% Medium

 

백준 단계에서 34단계 .. 

 

잘 이해해 보자..

 

http://www.goodtecher.com/leetcode-144-binary-tree-preorder-traversal/

 

LeetCode 144. Binary Tree Preorder Traversal - GoodTecher

Description https://leetcode.com/problems/binary-tree-preorder-traversal/description/ Given a binary tree, return the preorder traversal of its nodes’ values. For example: Given binary tree {1,#,2,3}, 1 \ 2…

www.goodtecher.com

 

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List preorderTraversal(TreeNode root) {
        List result = new ArrayList<>();
        Stack stack = new Stack<>();
        
        if (root == null) {
            return result;
        }
        
        stack.push(root);
        while (!stack.empty()) {
            TreeNode node = stack.pop();
            result.add(node.val);
            
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        
        return result;
    }
}

반응형

댓글