前序遍历
根-左儿子-右儿子
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void preorder(TreeNode *root, vector<int> &v) {
if (root == NULL) return;
v.push_back(root->val);
preorder(root->left,v);
preorder(root->right,v);
}
非递归遍历时就是模拟栈,注意入栈顺序即可
void preorder(TreeNode *root, vector<int> &v) {
if (root == NULL) return;
stack<TreeNode*> s;
s.push(root);
while (!s.empty()) {
TreeNode *p = s.top();
s.pop();
if (p == NULL) continue;
v.push_back(p->val);
s.push(p->right);
s.push(p->left);
}
}
中序遍历
左二子-根-右儿子
void inorder(TreeNode *root, vector<int> &v) {
if (root == NULL) return;
inorder(root->left, v);
v.push_back(root->val);
inorder(root->right,v);
}
非递归遍历时要保证访问根节点前已经访问完左二子
void inorder(TreeNode *root, vector<int> &v) {
if (root == NULL) return;
stack<TreeNode*> s;
TreeNode* p = root;
while (p || !s.empty()) {
while (p) {
s.push(p);
p = p->left;
}
if (!s.empty()) {
p = s.top();
v.push_back(p->val);
s.pop();
p = p->right; //这里利用right为空或者非空来避开p重复进while
}
}
}
后序遍历
左儿子-右儿子-根
void postorder(TreeNode *root, vector<int> &v) {
if (root == NULL) return;
postorder(root->left, v);
postorder(root->right, v);
v.push_back(root->val);
}
后序遍历要保证儿子们都遍历完了才访问根。用一个辅助节点pre记录上次访问的节点,则输出该节点时只有该节点为叶子节点或者pre为其儿子。否则把其儿子加入栈
void postorder(TreeNode *root, vector<int> &v) {
if (root == NULL) return;
stack<TreeNode*> s;
TreeNode* cur = root;
TreeNode* pre = NULL;
s.push(root);
while (!s.empty()) {
cur = s.top();
if ((cur->left == NULL && cur->right == NULL)||((pre)&&(pre == cur->left || pre == cur->right))){
v.push_back(cur->val);
pre = cur;
s.pop();
}
else { //入栈和访问节点是不同循环的。因为已经访问了该节点说明其儿子节点已经被访问过了,不能再入栈
if(cur->right) s.push(cur->right);
if(cur->left) s.push(cur->left);
}
}
}