zoukankan      html  css  js  c++  java
  • 二叉树的创建

    import java.util.*;
    public class Tree{
        static LinkedList<Node> nodelist = null;
        class Node{
            Node left;
            Node right;
            int data;
            public Node(int data){
                this.data = data;
            }
        }
        public void createTree(int[] array){
             nodelist = new LinkedList<Node>();
            for(int i=0;i<array.length;i++){
                Node n = new Node(1);
                nodelist.add(new Node(array[i]));
            }
            for(int i=0;i<array.length/2-1;i++){
                nodelist.get(i).left = nodelist.get(i*2+1);
                nodelist.get(i).right = nodelist.get(i*2+2);
            }
            int lastIndex = array.length/2-1;
            nodelist.get(lastIndex).left = nodelist.get(lastIndex*2+1);
            if(array.length%2==1){
                nodelist.get(lastIndex).right = nodelist.get(lastIndex*2+2);
            }
        }
        public void preOrderTraverse(Node node){
            if(node == null) return ;
            System.out.println(node.data);
            preOrderTraverse(node.left);
            preOrderTraverse(node.right);
        }
        public static void main(String[] args){
            int[] array = {4,3,5,6,2,9,1};
            Tree t = new Tree();
            t.createTree(array);
            t.preOrderTraverse(nodelist.get(0));
        }
    }

    1. 父节点数组下标从0到 n/2 -1 ,但是遍历时要小于n/2-1,因为最后一个父节点可能没有右孩子,当n/2-1为奇数时才有右孩子,为偶数时只有左孩子。

    2. 结点左孩子下标为2n+1,右孩子下标为2n+2。

  • 相关阅读:
    D2. Remove the Substring (hard version)(思维 )
    暑假集训
    AcWing:167. 木棒(dfs + 剪枝)
    AcWing:109. 天才ACM(倍增 + 归并排序)
    AcWing:99. 激光炸弹(前缀和)
    B. Interesting Array(线段树)
    Best Reward HDU
    G. Swapping Places
    How many HDU
    GSS4&&花仔游历各国
  • 原文地址:https://www.cnblogs.com/yingpu/p/9271286.html
Copyright © 2011-2022 走看看