zoukankan      html  css  js  c++  java
  • 前序遍历、中序遍历、后序遍历、层次遍历

    一、概念

    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);
                }
            }
        }
    }
    
  • 相关阅读:
    金融市场的初步了解
    今天参加了一个猎头实践
    前端面试
    web前端 浏览器私有前缀
    背景渐变
    移动web开发之响应式开发
    移动WEB开发之rem适配布局
    flex布局
    常见快捷方式
    virtual
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10658222.html
Copyright © 2011-2022 走看看