没事总喜欢写二叉树, 发现这东西把脑袋开启
今年任务, 加密安全字符集, 内存篇,网络篇,数据存储篇,加油
package com.he.test; /** * happy new year * * @author hejb * */ public class Start { class Node { public Node(long value, int level) { this.value = value; this.level = level; } public Long value; public int level; public Node leftNode; public Node rigtNode; } public static long max = 7; public static Node root; public Start(long value) { root = new Node(value, 0); } public void insetTree(Node node, long value, int level) { level++; if (value < node.value) { if (node.leftNode == null) { Node nodeItem = new Node(value, level); node.leftNode = nodeItem; } else { insetTree(node.leftNode, value, level); } } else { if (node.rigtNode == null) { Node nodeItem = new Node(value, level); node.rigtNode = nodeItem; } else { insetTree(node.rigtNode, value, level); } } } // 前序遍历 public void printNode(Node node) { System.out.println("节点值:" + node.value + ",属于树的第--->" + node.level + "层"); if (node.leftNode != null) { printNode(node.leftNode); } if (node.rigtNode != null) { printNode(node.rigtNode); } } public void printTree() { printNode(root); } public void insert(int value) { insetTree(root, value, 0); } public static void main(String[] args) { Start s = new Start(5); s.insert(4); s.insert(6); s.insert(3); s.insert(10); s.insert(8); s.insert(5); s.printTree(); } }
应该是生成下面这个树
5 4 6 3 5 8 1
输出
节点值:5,属于树的第--->0层
节点值:4,属于树的第--->1层
节点值:3,属于树的第--->2层
节点值:6,属于树的第--->1层
节点值:5,属于树的第--->2层
节点值:10,属于树的第--->2层
节点值:8,属于树的第--->3层
转载于:https://my.oschina.net/u/867417/blog/832555