Reference to 94
2ND TRY
100.00 %
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> deque = new ArrayDeque<>();
TreeNode curr = root;
while (curr != null || !deque.isEmpty()) {
while (curr != null) {
result.add(curr.val);
deque.addFirst(curr);
curr = curr.left;
}
curr = deque.removeFirst();
curr = curr.right;
}
return result;
}
}
1ST TRY
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if (root == null) return result;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode curr = root;
stack.push(root);
while (!stack.isEmpty()) {
curr = stack.pop();
result.add(curr.val);
if (curr.right != null) stack.push(curr.right);
if (curr.left != null) stack.push(curr.left);
}
return result;
}
}
No comments:
Post a Comment