Problem:
Given a binary tree, return the preorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3} ,
1 2 / 3
Return [1,2,3] .
Note: Recursive solution is trivial, could do it iteratively?
Hide TagsTree StackTest instructions: Non-recursive pre-order traversal binary tree
Thinking:
(1) The recursive method of the pre-sequence traversal is very easy, the subject requires non-recursion, with the help of stack implementation
(2) The idea is: not empty, the priority of the left child of the node into the stack, when the stack is access to the node value, if the left child is empty, take the top node of the stack, access to their right child, and then repeat the above step.
Code
Class Solution {public: vector<int> preordertraversal (treenode* root) { vector<int> ret; Stack<treenode *> _stack; TreeNode *node = root; while (Node!=null | |! _stack.empty ()) { if (node!=null) { ret.push_back (node->val); _stack.push (node); node=node->left; } else { node=_stack.top (); _stack.pop (); node=node->right; } } return ret; }};
Leetcode | | 144. Binary Tree Preorder Traversal