前序遍历、中序遍历、后序遍历、层次遍历

一、概念

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 代码

扫描二维码关注公众号,回复: 5785464 查看本文章
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);
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/wylwyl/p/10658222.html