首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >排序二叉树-添加以及遍历

排序二叉树-添加以及遍历

作者头像
shengjk1
发布于 2020-06-16 16:17:20
发布于 2020-06-16 16:17:20
5330
举报
文章被收录于专栏:码字搬砖码字搬砖
排序二叉树

对于任何一个非叶子节点,要求左子树的值比当前节点的值小,右子树的值比当前节点的值大。如果有相同的值,则可以放置左右任意节点

添加及遍历
代码语言:javascript
复制
package xmht.datastructuresandalgorithms.datastructure.binarysortTree;

/**
 * @author shengjk1
 * @date 2020/6/15
 */
public class BinarySortTree {
	public static void main(String[] args) {
		int[] arr = {7, 3, 10, 12, 5, -1, 9};
		BinarySortTree1 binarySortTree = new BinarySortTree1();
		for (int i : arr) {
			binarySortTree.add(new Node(i));
		}
		System.out.println("中序遍历二叉树");
		binarySortTree.infixOrder();
	}
}

class BinarySortTree1 {
	private Node root;
	
	public void add(Node node) {
		if (this.root != null) {
			this.root.add(node);
		} else {
			root = node;
		}
	}
	
	public void infixOrder() {
		if (this.root != null) {
			this.root.infixOrder();
		}
	}
	
	@Override
	public String toString() {
		return "BinarySortTree1{" +
				"root=" + root +
				'}';
	}
}

class Node {
	int value;
	Node left;
	Node right;
	
	public Node(int value) {
		this.value = value;
	}
	
	
	//添加节点
	//递归的形式添加,需要满足二叉排序树的要求
	public void add(Node node) {
		if (node == null) {
			return;
		}
		//判断传入节点的值,和当前子树的根节点的值的关系
		if (node.value < this.value) {
			if (this.left == null) {
				this.left = node;
			} else {
				//递归的向左子树添加
				this.left.add(node);
			}
		} else {
			if (this.right == null) {
				this.right = node;
			} else {
				this.right.add(node);
			}
		}
	}
	
	//中序遍历
	public void infixOrder() {
		if (this.left != null) {
			this.left.infixOrder();
		}
		System.out.println(this);
		
		if (this.right != null) {
			this.right.infixOrder();
		}
	}
	
	
	@Override
	public String toString() {
		return "Node{" +
				"value=" + value +
				'}';
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020/06/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 排序二叉树
  • 添加及遍历
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档