144 Binary Tree Preorder Traversal
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].
Solution:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
if ( root == NULL ) return result;
stack<TreeNode*> s;
s.push(root);
TreeNode* tnode;
while ( ! s.empty() ) {
tnode = s.top();
s.pop();
result.push_back(tnode->val);
if ( tnode->right != NULL ) s.push(tnode->right);
if ( tnode->left != NULL ) s.push(tnode->left);
}
return result;
}
};
Notes
For a given node,
- print its value
- push its right child
- push its left child