1. Front, middle and back order traversal
1. The concept of front, middle and back order traversal
The front, middle and back order traversal is actually based on the traversal order of child nodes and parent nodes.
Preface: middle left and right
Middle order: left center right
Sequence: left, right, middle
Tip: If the middle is in the front, it is preorder traversal, if the middle is in the middle, it is inorder, and if it is in the back, it is postorder.
Here, middle represents the parent node, left represents the left node (left child), and right represents the right node (right child).
The following is the order corresponding to the three traversal methods:
前序:10->9->6->5->7->4->3
中序:6->9->5->10->4->7->3
后序:6->5->9->4->3->7->10
2. Code implementation
prologue:
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& nums) {
if (cur == NULL) return;
nums.push_back(cur->val); //将父节点放进去即(中)
traversal(cur->left, nums); //放(左)
traversal(cur->right, nums); //放(右)
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
Mid-order:
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& nums) {
if (cur == NULL) return;
traversal(cur->left, nums); //放(左)
nums.push_back(cur->val); //将父节点放进去即(中)
traversal(cur->right, nums); //放(右)
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};
Afterword:
class Solution {
public:
void traversal(TreeNode* cur, vector<int>& nums) {
if (cur == NULL) return;
traversal(cur->left, nums); //放(左)
traversal(cur->right, nums); //放(右)
nums.push_back(cur->val); //将父节点放进去即(中)
}
vector<int> preorderTraversal(TreeNode* root) {
vector<int> result;
traversal(root, result);
return result;
}
};