二叉树的探讨与理解

 二叉树的题目普遍可以用递归和迭代的方式来解

前序遍历:根 -> 左 -> 右

中序遍历:左 -> 根 -> 右

后序遍历:左 -> 右 -> 根

/**
 * 
 */
package BinaryTree;

/**
 * @author heqy
 * @date 2018年2月7日 上午10:11:24
 * @description 二叉树创建和遍历
 */

public class BinaryTree {
	private Node root;

	/**
	 * 内部节点类
	 */
	private class Node {
		private Node left;
		private Node right;
		private int data;

		public Node(int data) {
			this.left = null;
			this.right = null;
			this.data = data;
		}
	}

	/** 构造方法 */
	public BinaryTree() {
		root = null;
	}

	/**
	 * 递归创建二叉树
	 * 
	 * @param node
	 * @param data
	 */
	public void buildTree(Node node, int data) {
		if (root == null) {
			root = new Node(data);
		} else {
			if (data < node.data) {
				if (node.left == null) {
					node.left = new Node(data);
				} else {
					buildTree(node.left, data);
				}
			} else {
				if (node.right == null) {
					node.right = new Node(data);
				} else {
					buildTree(node.right, data);
				}
			}
		}
	}

	/**
	 * 前序遍历
	 * 
	 * @param node
	 */
	public void preOrder(Node node) {
		if (node != null) {
			System.out.println(node.data);
			preOrder(node.left);
			preOrder(node.right);
		}
	}

	/**
	 * 中序遍历
	 * 
	 * @param node
	 */
	public void inOrder(Node node) {
		if (node != null) {
			inOrder(node.left);
			System.out.println(node.data);
			inOrder(node.right);
		}
	}

	/**
	 * 后序遍历
	 * 
	 * @param node
	 */
	public void postOrder(Node node) {
		if (node != null) {
			postOrder(node.left);
			postOrder(node.right);
			System.out.println(node.data);
		}
	}

	public static void main(String[] args) {
		char[] a = { 2, 4, 12, 45, 21, 6, 111 };
		BinaryTree bTree = new BinaryTree();
		for (int i = 0; i < a.length; i++) {
			bTree.buildTree(bTree.root, a[i]);
		}

		System.out.println("开始前序遍历");
		bTree.preOrder(bTree.root);

		System.out.println("开始中序遍历");
		bTree.inOrder(bTree.root);

		System.out.println("开始后序遍历");
		bTree.postOrder(bTree.root);
	}

}

为更好理解前序、中序、后序遍历,画图解:





猜你喜欢

转载自blog.csdn.net/m0_37721946/article/details/79428395