二叉树的遍历
前序遍历
- 访问根节点
- 前序遍历左子树
- 前序遍历右子树
(根左右)1 2 3 4 5 6 7 8
void preorder(TreeNode* root) { if(root == NULL){ return; } cout << root->val << endl; // 根 preorder(root->left); // 左 preorder(root->right); // 右 }
中序遍历
- 中序遍历左子树
- 访问根节点
- 中序遍历右子树
(左根右)1 2 3 4 5 6 7 8
void inorder(TreeNode* root) { if(root == NULL){ return; } inorder(root->left); // 左 cout << root->val << endl; // 根 inorder(root->right); // 右 }
后序遍历
- 后序遍历左子树
- 后序遍历右子树
- 访问根节点
(左右根)1 2 3 4 5 6 7 8
void postorder(TreeNode* root) { if(root == NULL){ return; } postorder(root->left); // 左 postorder(root->right); // 右 cout << root->val << endl; // 根 }