leetcode上的相关题目:
前序:https://leetcode.com/problems/binary-tree-preorder-traversal/?tab=Description
中序:https://leetcode.com/problems/binary-tree-inorder-traversal/?tab=Description
后序:https://leetcode.com/problems/binary-tree-postorder-traversal/?tab=Description
前序遍历很简单,先把当前节点的值保存到ret中,然后再把它的右孩子节点、左孩子节点分别压入stack中。注意是先右后左。
class Solution {
public:
vector preorderTraversal(TreeNode* root) {
vector ret;
stack s;
s.push(root);
while(!s.empty()){
TreeNode* cur = s.top();
s.pop();
if(cur != NULL){
ret.push_back(cur->val);
s.push(cur->right);
s.push(cur->left);
}
}
return ret;
}
};
根据中序遍历的顺序,对于任一结点,优先访问其左孩子,而左孩子结点又可以看做一根结点,然后继续访问其左孩子结点,直到遇到左孩子结点为空的结点才进行访问,然后按照相同的规则访问其 右子树。因此处理过程如下:
对任一结点p
1.若其左孩子不为空,则将p入栈并将p的左孩子置为当前的p,然后对当前结点p再进行相同的处理;
2.若其左孩子为空,则取栈顶元素并进行出栈操作,访问该栈顶结点,然后将栈顶结点的右孩子置为当前的p
3.直到p为null且栈为空则结束遍历
class Solution {
public:
vector inorderTraversal(TreeNode* root) {
vector ret;
stack s;
TreeNode* p = root;
while(p || !s.empty()){
while(p != NULL){
s.push(p);
p = p -> left;
}
TreeNode* cur = s.top();
s.pop();
ret.push_back(cur->val);
p = cur -> right;
}
return ret;
}
};
class Solution {
public:
//按照和前序相似的思想,然后再倒一次顺序即可
vector postorderTraversal(TreeNode* root) {
vector ret;
stack s;
s.push(root);
while(!s.empty()){
TreeNode* cur = s.top();
s.pop();
if(cur != NULL){
ret.push_back(cur->val);
s.push(cur->left); //前序遍历时,是先右后左的。这里先左后右。
s.push(cur->right);
}
}
reverse(ret.begin(), ret.end());
return ret;
}
};