先序遍历(前序遍历):
遍历顺序规则为 根->左->右
递归:
void preOrder(TreeNode* root) { if (!root) { return; } cout << root->val; preOrder(root->left); preOrder(root->right); }
非递归:
void preorder_traversal_iteratively(TreeNode* root) { if (root == 0) return; stack<TreeNode*> s; s.push(root); cout << root->val << ' '; // visit root TreeNode* last_pop = root; while (!s.empty()) { TreeNode* top = s.top(); if (top->left != 0 && top->left != last_pop && top->right != last_pop) // push_left { s.push(top->left); cout << top->left->val << ' '; // visit top->left } else if (top->right != 0 && top->right != last_pop && (top->left == 0 || top->left == last_pop)) // push_right { s.push(top->right); cout << top->right->val << ' '; // visit top->right } else // pop { s.pop(); last_pop = top; } } }
中序遍历:
遍历顺序规则为 左->根->右
递归:
void inOrder(TreeNode* root) { if (!root) { return; } inOrder(root->left); cout << root->val; inOrder(root->right); }
非递归:
void inorder_traversal_iteratively(TreeNode* root) { if (root == 0) return; stack<TreeNode*> s; s.push(root); TreeNode* last_pop = root; while (!s.empty()) { TreeNode* top = s.top(); if (top->left != 0 && top->left != last_pop && top->right != last_pop) // push_left { s.push(top->left); } else if (top->right != 0 && top->right != last_pop && (top->left == 0 || top->left == last_pop)) // push_right { s.push(top->right); cout << top->val << ' '; // visit top } else // pop { s.pop(); last_pop = top; if (top->right == 0) cout << top->val << ' '; // visit top } } }
后序遍历:
遍历顺序规则为 左->右->根
递归:
void postOrder(TreeNode* root) { if (!root) { return; } postOrder(root->left); postOrder(root->right); cout << root->val; }
非递归:
void postorder_traversal_iteratively(TreeNode* root) { if (root == 0) return; stack<TreeNode*> s; s.push(root); TreeNode* last_pop = root; while (!s.empty()) { TreeNode* top = s.top(); if (top->left != 0 && top->left != last_pop && top->right != last_pop) // push_left { s.push(top->left); } else if (top->right != 0 && top->right != last_pop && (top->left == 0 || top->left == last_pop)) // push_right { s.push(top->right); } else // pop { s.pop(); last_pop = top; cout << top->val << ' '; // visit top } } }
7809

被折叠的 条评论
为什么被折叠?



