二叉树

作者: 正义的米卡塔 | 来源:发表于2016-02-26 18:33 被阅读39次

    闲来没事,学习了下二叉树

    public class TreeNode {

    /**

    * 左边节点

    */

    public TreeNode leftTree;

    /**

    * 右边节点

    */

    public TreeNode rightTree;

    /**

    * 数据

    */

    public int iDate;

    public int parent;

    public TreeNode(int i) {

    // TODO Auto-generated constructor stub

    this.iDate = i;

    }

    public void displayNode() {

    }

    public void add(TreeNode root, int idate) {

    // parent=root;

    TreeNode node = find(root, idate);

    if (node != null) {

    if (node.iDate < idate) {

    node.rightTree = new TreeNode(idate);

    node.rightTree.parent=node.iDate;

    } else {

    node.leftTree = new TreeNode(idate);

    node.leftTree.parent=node.iDate;

    }

    }

    }

    private TreeNode find(TreeNode root, int i) {

    // TODO Auto-generated method stub

    if (root.iDate < i) {

    if (root.rightTree != null) {

    return find(root.rightTree, i);

    } else {

    return root;

    }

    } else {

    if (root.leftTree != null) {

    return find(root.leftTree, i);

    } else {

    return root;

    }

    }

    }

    }

    ----------------------------------

    public class TreeTest {

    public static int[] temp={7,3,9,8,10,2,1};

    public static void main(String[] args) {

    TreeNode node=new TreeNode(5);

    for (int i = 0; i < temp.length; i++) {

    node.add(node,temp[i]);

    }

    System.out.println(node);

    // node.find(3);

    }

    }

    相关文章

      网友评论

          本文标题:二叉树

          本文链接:https://www.haomeiwen.com/subject/frdwkttx.html