144. Binary Tree Preorder Traversal
Given a binary tree, return thepreordertraversal of its nodes' values.
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
TreeNode curNode = root, preNode = null;
while (curNode != null) {
if (curNode.left == null) {
res.add(curNode.val);
curNode = curNode.right;
}
else {
preNode = curNode.left;
while (preNode.right != null && preNode.right != curNode) {
preNode = preNode.right;
}
if (preNode.right == null) {
res.add(curNode.val);
preNode.right = curNode;
curNode = curNode.left;
}
else {
preNode.right = null;
curNode = curNode.right;
}
}
}
return res;
}
}
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode curNode = null;
while (!stack.isEmpty()) {
curNode = stack.pop();
res.add(curNode.val);
if (curNode.right != null) {
stack.push(curNode.right);
}
if (curNode.left != null) {
stack.push(curNode.left);
}
}
return res;
}
}
3. Time & Space Complexity