Binary Tree Preorder Traversal
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]
解析
树的前序遍历,方法类似于Binary Tree Inorder Traversal中序遍历。
解法1:递归
构建一个辅助函数,进行递归。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
preorder(root, res);
return res;
}
void preorder(TreeNode* root, vector<int> &res){
if(!root) return;
res.push_back(root->val);
preorder(root->left, res);
preorder(root->right, res);
}
};
解法2:迭代
使用stack保存节点,思路是从根节点开始,先将根节点压入栈,然后右节点入栈,左节点入栈,然后取出栈顶节点,保存节点值,这样就保证了访问顺序为根-左-右。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
s.push(root);
while(!s.empty()){
TreeNode* p = s.top();
s.pop();
res.push_back(p->val);
if(p->right)
s.push(p->right);
if(p->left)
s.push(p->left);
}
return res;
}
};
解法3:迭代模板
使用了一个辅助结点p,前中后遍历的模板。.辅助结点p初始化为根结点,while循环的条件是栈不为空或者辅助结点p不为空,在循环中首先判断如果辅助结点p存在,那么先将p加入栈中,然后将p的结点值加入结果res中,此时p指向其左子结点。否则如果p不存在的话,表明没有左子结点,我们取出栈顶结点,将p指向栈顶结点的右子结点。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
TreeNode* p = root;
while(p || !s.empty()){
if(p){
s.push(p);
res.push_back(p->val);
p = p->left;
}
else{
TreeNode* node = s.top();
s.pop();
p = node->right;
}
}
return res;
}
};
解法4:Morris遍历空间复杂度O(1)
类似于Binary Tree Inorder Traversal中序遍历的Morris遍历步骤。只是在节点添加的顺序不同。
具体算法:
1. 如果当前节点的左孩子为空,则输出当前节点并将其右孩子作为当前节点。
2. 如果当前节点的左孩子不为空,在当前节点的左子树中找到当前节点在中序遍历下的前驱节点。
a) 如果前驱节点的右孩子为空,将它的右孩子设置为当前节点。输出当前节点(在这里输出,这是与中序遍历唯一一点不同)。当前节点更新为当前节点的左孩子。
b) 如果前驱节点的右孩子为当前节点,将它的右孩子重新设为空(恢复树的形状)。输出当前节点。当前节点更新为当前节点的右孩子。
3. 重复以上1、2直到当前节点为空。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
TreeNode* cur = root;
TreeNode* pre;
while(cur){
if(!cur->left){
res.push_back(cur->val);
cur = cur->right;
}
else{
pre = cur->left;
while(pre->right && pre->right != cur)
pre = pre->right;
if(!pre->right){
res.push_back(cur->val); // 唯一与中序遍历Morris不同的地方
pre->right = cur;
cur = cur->left;
}
else{
pre->right = NULL;
cur = cur->right;
}
}
}
return res;
}
};
参考
http://www.cnblogs.com/grandyang/p/4146981.html
Binary Tree Inorder Traversal
http://www.cnblogs.com/AnnieKim/archive/2013/06/15/morristraversal.html