Java教程

Java--算法--二叉树

本文主要是介绍Java--算法--二叉树,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
  1. 二叉树的基本介绍:
    1.  

       

       

      1. package com.model.tree;
        
        import java.util.ArrayDeque;
        import java.util.Deque;
        
        /**
         * @Description:测试类
         * @Author: 张紫韩
         * @Crete 2021/8/17 21:50
         * 树的遍历
         */
        public class TreeDemo02 {
            public static void main(String[] args) {
                TreeNode root = new TreeNode(0);
                TreeNode left = new TreeNode(1);
                TreeNode right = new TreeNode(2);
                TreeNode  left_left = new TreeNode(3);
                TreeNode right_right = new TreeNode(4);
                root.left=left;
                root.right=right;
                left.left=left_left;
                right.right=right_right;
        //        preOrder(root);
        //        midOrder(root);
        //        postOrder(root);
                sequenceOrder(root);
        
            }
        // 层序遍历
            public static void sequenceOrder(TreeNode root){
                if (root==null){
                    return;
                }
                Deque<TreeNode> deque=new ArrayDeque<>();
                deque.add(root);
                while (!deque.isEmpty()){
                    TreeNode cur = deque.pop();
                    System.out.println(cur);
                    if (cur.left!=null){
                        deque.add(cur.left);
                    }
                    if (cur.right!=null){
                        deque.add(cur.right);
                    }
                }
            }
        
        
        //    先序遍历方式
            public static void preOrder(TreeNode root){
                if (root==null){
                    return;
                }
                System.out.println(root);
                preOrder(root.left);
                preOrder(root.right);
            }
        
            public static void midOrder(TreeNode root){
                if (root==null){
                    return;
                }
                midOrder(root.left);
                System.out.println(root);
                midOrder(root.right);
            }
            public static void postOrder(TreeNode root){
                if (root==null){
                    return;
                }
                postOrder(root.left);
                postOrder(root.right);
                System.out.println(root);
            }
        }
    2.  

        
这篇关于Java--算法--二叉树的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!