二叉树

Posted by Marlin on May 2, 2025

二叉树的遍历

前序遍历

  1. 访问根节点
  2. 前序遍历左子树
  3. 前序遍历右子树
    (根左右)
    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. 中序遍历右子树
    (左根右)
    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. 访问根节点
    (左右根)
    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; // 根
    }