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]
.
Note: Recursive solution is trivial, could you do it iteratively?
Code:
1. Recursive:
class Solution { public: void findNode(vector<int> &nodes,TreeNode *node){ nodes.push_back(node->val); if(node->left) findNode(nodes,node->left); if(node->right) findNode(nodes,node->right); return; } vector<int> preorderTraversal(TreeNode *root) { vector<int> nodes; if(!root) return nodes; findNode(nodes,root); return nodes; } };