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.  

        
posted @ 2021-08-18 21:50  张紫韩  阅读(65)  评论(0编辑  收藏  举报