144. 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题
stack迭代或 morris遍历(空间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) {
if(!root) return res;
S.push(root);
TreeNode *tmp;
while(!S.empty()){
tmp=S.top();
S.pop();
res.push_back(tmp->val);
if(tmp->right) S.push(tmp->right);
if(tmp->left) S.push(tmp->left);
}
return res;
}
private:
stack<TreeNode *> S;
vector<int> 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) {
TreeNode* cur;
while(root){
res.push_back(root->val);
cur=root;
if(cur->left){
TreeNode *tmp;
tmp=cur->right;
cur->right=cur->left;
cur->left=NULL;
while(cur->right) cur=cur->right;
cur->right=tmp;
}
root=root->right;
}
return res;
}
private:
vector<int> res;
};
MORRIS:不改变树结构
前序遍历与中序遍历,其压入数组的位置不同而已;
步骤
(1)第一次遍历,有左子树,把左子树的最右指向自己,自己压入数组,遍历左子树;
(2)第一次遍历,无左子树,把自己压入数组,遍历右子树;
(3)第二次遍历(有左子树,且右子树中找到自己),将指向自己的结点指向null(复原),进入右子树,不压入数组;
注意点
前序遍历时,压入数组的位置为
(1)第一次遍历有左子树的点时;
(2)以及第一个遍历无左子树的点时;
中序遍历时,压入数组的位置为
(1)第二次遍历有左子树的点时;
(2)第一次遍历无左子树的点时;
/**
* 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) {
TreeNode* cur=root;
TreeNode * tmp;
while(cur){
if(cur->left){
tmp=cur->left;
while(tmp->right&&tmp->right!=cur) tmp=tmp->right;
if(!tmp->right) {
tmp->right=cur;
res.push_back(cur->val); //先于左子树 第一次添加的时候加入
cur=cur->left;
}
else {
tmp->right=NULL; //复原
cur=cur->right;
}
}
else {
res.push_back(cur->val); //无左子树也加入
cur=cur->right;
}
}
return res;
}
private:
vector<int> res;
};
145. 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,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> postorderTraversal(TreeNode* root) {
if(!root) return res;
S.push(root);
TreeNode *tmp;
while(!S.empty()){ //根 右 左 // 左 右 根
tmp=S.top();
S.pop();
res.push_back(tmp->val);
if(tmp->left) S.push(tmp->left);
if(tmp->right) S.push(tmp->right);
}
reverse(res.begin(),res.end());
return res;
}
private:
vector<int> res;
stack<TreeNode *> S;
};