Binary tree preorder traversal binary-tree-preorder-traversal
Title description
Find the preorder traversal of the given binary tree.
For example:
the given binary tree is {1,#,2,3},
1↵ ↵ 2↵ /↵ 3↵Return
: [1,2,3].
Remarks; using recursion to solve this problem is too new, Can an iterative solution be given?
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?
Problem-solving ideas
Idea 1: Recursion
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL) return res;
preorder(root, res);
return res;
}
void preorder(TreeNode* root, vector<int>& res) {
if(root == NULL) return ;
res.push_back(root -> val);
preorder(root -> left, res);
preorder(root -> right, res);
}
};
Idea 2: Iteration
- The overall writing is very similar to the level traversal, the difference is:
- The pre-order traversal uses the stack, and the level traversal uses the queue
- Preorder traversal because the output is left and right. According to the first-in-last-out characteristics of the stack, when entering the stack, the stack is first right and then left , while the level traversal is first left and then right into the queue.
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(root == NULL) return res;
stack<TreeNode*> mystack;
mystack.push(root);
while(!mystack.empty()) {
TreeNode* temp = mystack.top();
mystack.pop();
res.push_back(temp -> val);
//先右后左
if(temp -> right) mystack.push(temp -> right);
if(temp -> left) mystack.push(temp -> left);
}
return res;
}
};