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 a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void trans(vector<int> &res, TreeNode* root) {
res.push_back(root->val);
if(root->left) trans(res, root->left);
if(root->right) trans(res, root->right);
return ;
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root)
return res;
trans(res, root);
return res;
}
};
接下来是迭代方法:
/**
* 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> res;
if(root == NULL) return res;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()) {
TreeNode* cur = st.top();
st.pop();
while(cur != NULL) {
res.push_back(cur->val);
if(cur->right) {
st.push(cur->right);
}
cur = cur->left;
}
}
return res;
}
};