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?
/** * Definition for binary tree * 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> ans; iter(root,ans); return ans; } void iter(TreeNode *root, vector<int>& vec) { if(root == NULL) return; vec.push_back(root->val); iter(root->left,vec); iter(root->right,vec); } };
浙公网安备 33010602011771号