Binary Tree Preorder Traversal

LeetCode Q 144 - Binary Tree Preorder Traversal

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

Follow up: Recursive solution is trivial, could you do it iteratively?

Similar Questions: Inorder Traversal, Postorder Traversal

Solution

Code:

public List<Integer> preorderTraversal(TreeNode root) {
	List<Integer> res = new ArrayList<>();
	if (root == null) return res;

	Stack<TreeNode> stack = new Stact<>();
	stack.push(root);
	while (!stack.isEmpty()) {
		TreeNode curr = stack.pop();
		res.add(curr.val);
		if (curr.right != null) stack.push(curr.right);
		if (curr.left != null) stack.push(curr.left);
	}

	return res;
}

   Reprint policy


《Binary Tree Preorder Traversal》 by Tong Shi is licensed under a Creative Commons Attribution 4.0 International License
  TOC