Problem
Given a binary tree, return the preorder traversal of its nodes’ values.
Example:
1 |
|
Follow up: Recursive solution is trivial, could you do it iteratively?
Explanation 1
-
Preorder traversal is from root->left->right.
-
Think of a tree that only has root node, left child, and right child first. We push the root child to the result array, then push the left children, then the right children. For the left children, we can then think of it as a root node recursivly run the helper function to push the so called root node to the array.
Solution 1
1 |
|
Explanation 2
-
To use an iterativly method, we can create a stack and a pointer to the root node. This method is also applies to Binary Tree Inorder Traversal and Binary Tree Postorder Traversal.
-
Always start with while stack is not empty or p is not empty, because preorder traversal is root first, if the pointer node is not null, we can push the pointer node, which is the root node to the stack, and adding pointer node’s value to the result array. Then make the pointer points at the left child node, and repeat the while loop.
-
For example in the below tree, pointer is initiallized point at 1, enter the while loop, we push it to stack and 1 to array; then pointer points at 2, then push to stack, add 2 to result array; then pointer points at 2’s left child which is null, if pointer is null, then we move the pointer to pop stack’s right child which means pop stack node is 2, its right child is 3, then we push 3 to stack and add 3 to result array; now pointer is at 3’s left child which is null, we pop 3, pointer at 3’s right child which still null, we pop stack which getting 1, make pointer points at 1’s right child which is null. We break out the while loop since stack is empty and pointer is null and we finish.
1 |
|
Solution 2
1 |
|