Given a binary tree, return the preorder traversal of its nodes' values.
For example: Given binary tree {1,#,2,3},
1 \ 2 / 3return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
递归大法代码如下:
/** * 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; preorder(root,result); return result; } void preorder(TreeNode* root,vector<int>& result) { if(root == NULL) return; result.push_back(root->val); preorder(root->left,result); preorder(root->right,result); } };
迭代大法代码如下:
/** * 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; stack<TreeNode*> data; while(root) { if(root->right) data.push(root->right); result.push_back(root->val); root = root->left; if(root == NULL && !data.empty()) { root = data.top(); data.pop(); } } return result; } };