Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
考察:二叉树的前序遍历
Method 1. Recursive
/**
* 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) {
if (root == NULL)
return {};
vector<int> res;
preorderTraversal(root, res);
return res;
}
void preorderTraversal(TreeNode* root, vector<int>& res) {
if (root == NULL)
return ;
res.push_back(root->val);
if (root->left)
preorderTraversal(root->left, res);
if (root->right)
preorderTraversal(root->right, res);
}
};
Method 2.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) {
if (root == NULL)
return {};
stack<TreeNode*> s{{root}};
vector<int> res;
while(!s.empty()) {
TreeNode* cur = s.top();
s.pop();
res.push_back(cur->val);
if (cur->right)
s.push(cur->right);
if (cur->left)
s.push(cur->left);
}
return res;
}
};
完,