Title:
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?
Tips:
First, you need to clear the order of the pre-order traversal, that is, the left child-to-right child, node, which is traversed in this order.
A more flattering approach to this problem is to declare a vector member variable in the solution class so that you can push the element through the vector in a recursive way. However, if the requirement must be solved only by the given function, then you need to use the "stack" data structure to simulate the recursive invocation of the function, the method can refer to the implementation of the Code.
Code:
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right ; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: Vector<int> Preordertraversal (treenode*root) {Vector<int>result; Stack<TreeNode*>Node_stack; Node_stack.push (root); while(!Node_stack.empty ()) {TreeNode*node =Node_stack.top (); Node_stack.pop (); if(node = =NULL) { Continue; } Result.push_back (Node-val); Node_stack.push (Node-Right ); Node_stack.push (Node-Left ); } returnresult; }};
"Leetcode" 144. Binary Tree Preorder Traversal