标签:turn get treenode his 标准 相关 private 思考 它的
前两篇日志主要研究了二叉树的相关基本知识,以及二叉树的最基本的实现
package com.example.demo.dataStructure.binaryTree; public class BinarySortTree { public static void main(String[] args) { BinarySortTree bst = new BinarySortTree(); int array[] = {9,8,7,6,5,4,3,2,1}; TreeNode tree = bst.createBinarySortTree(array); bst.inOrderTraversal(tree); } public TreeNode root; public TreeNode createBinarySortTree(int[] num) { TreeNode tree = null; for(int i=0;i<num.length;i++) { tree = addNode(new TreeNode(num[i])); // 思考:创建一颗树的时候,根节点的选取标准,创建之后树的高度 } return tree; } /** * 中根遍历 */ public void inOrderTraversal(TreeNode tree) { if (null == tree) { return; } inOrderTraversal(tree.getLeftChild()); System.out.print(tree.getData()); inOrderTraversal(tree.getRightChild()); } /** * 添加节点 * @param node */ public TreeNode addNode(TreeNode node) { if (root == null) { root = node; return root; } TreeNode current = root; while(true) { if(node.getData() <= current.getData()) { // 插入节点的值小于等于当前节点的值,放左子树 if(current.getLeftChild() == null) { current.setLeftChild(node); return root; } current = current.getLeftChild(); } else { // 插入节点的值小于等于当前节点的值,放左子树 if(current.getRightChild() == null) { current.setRightChild(node); return root; } current = current.getRightChild(); } } } class TreeNode { private TreeNode leftChild; // 左孩子 private TreeNode rightChild; // 右孩子 private int data; // 数据部分 public TreeNode() { super(); } // 初始化节点 public TreeNode(TreeNode leftChild, TreeNode rightChild, int data) { super(); this.leftChild = leftChild; this.rightChild = rightChild; this.data = data; } // 初始化数据域 public TreeNode(int data) { this(null, null, data); } public TreeNode getLeftChild() { return leftChild; } public void setLeftChild(TreeNode leftChild) { this.leftChild = leftChild; } public TreeNode getRightChild() { return rightChild; } public void setRightChild(TreeNode rightChild) { this.rightChild = rightChild; } public int getData() { return data; } public void setData(int data) { this.data = data; } } }
后面有时间继续深入研究,这里面还是有很多问题的
标签:turn get treenode his 标准 相关 private 思考 它的
原文地址:https://www.cnblogs.com/xiaobaobei/p/9638183.html