> [144. Binary Tree Preorder Traversal](https://leetcode.com/problems/binary-tree-preorder-traversal/description/)
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?
分析:二叉树的基础知识
实现三种遍历方法:
1.递归,时间复杂度:O(n),空间复杂度:O(n)
2.迭代,时间复杂度:O(n),空间复杂度:O(n)
3.线索二叉树,时间复杂度:O(n),空间复杂度:O(1)
// 解法一:递归
/**
* 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;
preTraversal(root, result);
return result;
}
void preTraversal(TreeNode* root, vector<int>& result){
if(!root)
return;
result.push_back(root->val);
preTraversal(root->left, result);
preTraversal(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;
if(!root)
return result;
stack<TreeNode*> s;
TreeNode* temp = root;
while(temp || !s.empty()){
if(temp){
result.push_back(temp->val);
if(temp->right)
s.push(temp->right);
temp = temp->left;
}else{
temp = s.top();
s.pop();
}
}
return 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> v;
if(!root) return v;
TreeNode* temp = root, *prev;
while(temp){
if(!temp->left){
v.push_back(temp->val);
temp = temp->right;
}else{
prev = temp->left;
while(prev->right&&(prev->right != temp))
prev = prev->right;
if(!prev->right){
v.push_back(temp->val);
prev->right = temp;
temp = temp->left;
}else{
prev->right = NULL;
temp = temp->right;
}
}
}
return v;
}
};