前序遍歷、中序遍歷、后序遍歷、層次遍歷


一、概念

1、前序遍歷

  1. 先根節點
  2. 左節點
  3. 右節點

2、中序遍歷:

  1. 左節點
  2. 根節點
  3. 右節點

3、后序遍歷

  1. 左節點
  2. 右節點
  3. 根節點

4、層次遍歷

從上往下打印出二叉樹的每個結點,同一層的結點按照從左到右的順序打印

 

二、代碼

2.1 首先定義TreeNode

public class TreeNode {
    public int value;
    public TreeNode left;
    public TreeNode right;
}

  

2.2 代碼

import java.util.*;

public class Solution {

    public static preOrderTravel(TreeNode root) {
        if(root == null) {
            return;
        }

        System.out.println(root.val);
        if(root.left != null) {
            preOrderTravel(root.left);
        }

        if(root.right != null) {
            preOrderTravel(root.right);
        }
    }

    public static void inOrderTravel(TreeNode root) {
        if(root ==  null) {
            return;
        }

        if(root.left != null) {
            inOrderTravel(root.left);
        }

        System.out.println(root.val);

        if(root.right != null) {
            inOrderTravel(root.right);
        }
    }

    public static void postOrderTravel(TreeNode root) {
        if(root == null) {
            return;
        }

        if(root.left != null) {
            postOrderTravel(root.left);
        }

        if(root.right != null) {
            postOrderTravel(root.right);
        }

        System.out.println(root.val);
    }

    public static void fromTopToBottom(TreeNode root) {
        if(root == null) {
            return;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);

        while(queue.isEmpty()) {
            // 移除並返問隊列頭部的元素    如果隊列為空,則返回null
            TreeNode node = queue.poll();
            
            System.out.println(node.val);

            if(node.left != null) {
                queue.add(node.left);
            }

            if(node.right != null) {
                queue.add(node.right);
            }
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM