java——二叉树遍历

今天遇到一个面试题,构建一个二叉树,并分别打印四个分支。




import java.util.LinkedList;
import java.util.List;

public class BinaryTree {
	private String[] array = { "A", "B", "C", "D", "E", "F", "G" };
	private static List<Node> nodeList = null;

	private static class Node {
		Node leftChild;
		Node rightChild;
		String data;

		Node(String newData) {
			leftChild = null;
			rightChild = null;
			data = newData;
		}
	}

	public void createBinTree() {
		nodeList = new LinkedList<Node>();
		for (int i = 0; i < array.length; i++) {
			nodeList.add(new Node(array[i]));
		}
		for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
			// 左
			nodeList.get(parentIndex).leftChild = nodeList
					.get(parentIndex * 2 + 1);
			// 右
			nodeList.get(parentIndex).rightChild = nodeList
					.get(parentIndex * 2 + 2);
		}
		//last父节点
		int lastParentIndex = array.length / 2 - 1;
		//这里可以加判断,因为这里只有7个所以直接写了。
		nodeList.get(lastParentIndex).leftChild = nodeList.get(lastParentIndex * 2 + 1);
		nodeList.get(lastParentIndex).rightChild = nodeList.get(lastParentIndex * 2 + 2);
	}

	/**
	 * 遍历
	 */
	public static void post1(Node root) {
		if (root == null)
			return;
		System.out.print(root.data);
		post1(root.leftChild);
	}

	public static void post3(Node root) {
		if (root == null)
			return;
		System.out.print(root.data);
		post2(root.rightChild);
	}

	public static void post2(Node root) {
		if (root == null)
			return;
		System.out.print(root.data);
		post3(root.leftChild);
	}

	public static void post4(Node root) {
		if (root == null)
			return;
		System.out.print(root.data);
		post4(root.rightChild);
	}

	public static void main(String args[]) {
		BinaryTree tree = new BinaryTree();
		tree.createBinTree();
		Node root = nodeList.get(0);
		// 输出
		post1(root);
		System.out.println();
		post2(root);
		System.out.println();
		post3(root);
		System.out.println();
		post4(root);
	}
}

效果:


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值