스터디 알고리즘 문제1 Stack 정답률 54.3% Medium
백준 단계에서 34단계 ..
잘 이해해 보자..
http://www.goodtecher.com/leetcode-144-binary-tree-preorder-traversal/
/**
* 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;
}
}
'Leetcode' 카테고리의 다른 글
Leetcode <Sort> 242. Valid Anagram 백준 6996번 애너그램 (0) | 2020.04.05 |
---|---|
Leetcode 328. Odd Even Linked List 52.5% Medium (0) | 2020.04.03 |
Leetcode 621. Task Scheduler 47.7% Medium (0) | 2020.04.03 |
Leetcode <Heap> 264. Ugly Number II 38.9% Medium (0) | 2020.04.03 |
Leetcode 96. Unique Binary Search Trees 50.1% Medium (0) | 2020.04.03 |
댓글