• java之二叉树算法


    创建二叉树类

    public class tree {
        int data;
        tree left;
        tree right;
        public tree(int data, tree left, tree right) {
            super();
            this.data = data;
            this.left = left;
            this.right = right;
        }
        public tree(int data) {
            this.data=data;
            this.left=null;
            this.right=null;
        }
        public void  insert(tree t,int data){
            if(data>this.data){
                if(t.right==null){
                    t.right=new tree(data);
                }else{
                    t.insert(right,data);
                }
            }else if(data<=this.data){
                if(t.left==null){
                    t.left=new tree(data);
                }else{
                    t.insert(left,data);
                }
            }
        }
        
    }

    遍历二叉树

    public class BinaryTree {
    ;
        public static void main(String[] args) {
            int [] arr ={21,33,44,23,56,79,456,32,98,7,5};
            tree root = new tree(arr[0]);
            for (int i = 1; i < arr.length; i++) {
                root.insert(root,arr[i]);
            }
            preOrder(root);
        }
        public static void  preOrder(tree root){
            if(root!=null){
                System.out.print(root.data+"-");
                preOrder(root.left);
                preOrder(root.right);
            }
            //System.out.println("先根遍历");
        }
        
    
    }
  • 相关阅读:
    数组的反转和二维数组
    初识数组
    Python学习笔记-Day8
    Python学习笔记-Day7
    Python学习笔记-Day6
    Python学习笔记-Day5
    Python学习笔记-Day4
    Python学习笔记-Day3
    Python学习笔记-Day2
    Python学习笔记-Day1
  • 原文地址:https://www.cnblogs.com/wangyinxu/p/7402302.html
Copyright © 2020-2023  润新知