剑指offer面试题23 从上往下打印二叉树

考察点

树的遍历

知识点

题目

分析
题目要求从上到下打印二叉树,类似这种题目的思路就是用归纳法,通过一些例子找到数据的规律找一个合适的数据结构,这道题目很明显不能按照树的三种遍历方式去解,要按照6,10,5,7,9,11的顺序遍历,5和7是6的子结点,9和11是10的子结点,也就是说需要先遍历完父结点,再遍历子结点,同时在遍历父结点的时候要先把子结点存到这个数据结构里面,同时要求先入先出,那么很明显这个结构就是队列

import java.util.Queue;
import java.util.LinkedList;

public class BinaryTree {
	Node root;

	public BinaryTree() {
		this.root = null;
	}
	public void insertTree(int val) {
		if (this.root == null) {
			Node root = new Node(val);
			this.root = root;
		} else {
			insertChildTree(this.root,val);
		}
	}
	public void insertChildTree(Node node,int val) {
		if (node != null && val < node.val) {
			if (node.leftChild == null) {
				node.leftChild = new Node(val);
			} else {
				insertChildTree(node.leftChild,val);
			}
		}
		if (node != null && val > node.val) {
			if (node.rightChild == null) {
				node.rightChild = new Node(val);
			} else {
				insertChildTree(node.rightChild,val);
			}
		}
	}
	public Node getRoot() {
		return this.root;
	}
	public void levelPrint(Node root) {
		Queue q = new LinkedList<>();
		q.add(root);
		while(q.size() > 0) {
			Node node = (Node) q.remove();
			System.out.println(node.val);
			if (node.leftChild != null) {
				q.add(node.leftChild);
			}
			if (node.rightChild != null) {
				q.add(node.rightChild);
			}
		}
	}
}
public class Node{
	int val;
	Node leftChild;
	Node rightChild;

	public Node(int data) {
		this.val = data;
		this.leftChild = null;
		this.rightChild = null;
	}
}
public class TwentyThree {
	public static void main(String[] args) {
		BinaryTree tree = new BinaryTree();
		tree.insertTree(8);
		tree.insertTree(6);
		tree.insertTree(10);
		tree.insertTree(5);
		tree.insertTree(7);
		tree.insertTree(9);
		tree.insertTree(11);
		tree.levelPrint(tree.getRoot());
	}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值