Given a binary tree, return the preorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3},
return [+].
Note:recursive solution is trivial, could do it iteratively?
The first-order traversal should be the best use of non-recursive implementations in three traversal modes.
You can access a node each time and then put its right child node into the stack, and then the left child node into the stack. And then take the elements from the stack, you can find that is the result of the first order traversal. It is important to note that if the child node does not exist, it does not need to be in the stack operation.
Runtime:4ms
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *righ T * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: vector<int>Preordertraversal (treenode* root) { vector<int>Resif(Root==null)returnRes Stack<treenode *>S TreeNode * NODE=ROOT; S.push (node); while(!s.empty ()) {node=s.top (); S.pop (); Res.push_back (Node->val);if(node->right) S.push (node->right);if(node->left) S.push (node->left); }returnRes }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode144:binary Tree Preorder Traversal