根据前序、中序遍历重建二叉树(Java)

思路:

1、根据前序遍历找到根节点,根据中序遍历,找到根节点左侧所有节点

2、递归构建二叉树

 

代码:

package com.datastructure.tree;


/**
 * 根据前序和中序遍历队列,重建二叉树 
 */
public class BulidBinaryTree {

	static class Node {
        int value;
        Node left;
        Node right;
        Node(int value) {
            this.value = value;
        }
	}
	
	public static Node buildTree(int[] preOrder, int[] inOrder) {
		if (preOrder == null || inOrder == null 
				|| preOrder.length <= 0
				|| inOrder.length <= 0
				|| preOrder.length != inOrder.length) {
			return null;
		}
		int len = preOrder.length;
		return buildTree(preOrder, 0, len - 1, inOrder, 0, len - 1);
	}
	
	public static Node buildTree(int[] preOrder, int ps, int pe, 
			int[] inOrder, int is, int ie) {
		// 终止条件
		if (ps > pe) {
			return null;
		}
		
		// 获取头节点
		int rootVal = preOrder[ps];
		Node root = new Node(rootVal);
		
		// 获取左边和右边的节点数量
		
		int index = is;
		while(index <= ie && inOrder[index] != rootVal) {
			index++;
		}
		
		if (index > ie) {
			throw new RuntimeException("bad param");
		}
		
		// 构建左右子树
		// 当前左子树元素的数量为index-is个
		// 除去 当前根节点的继续寻找,及preOrder[ps] inOrder[index]
		root.left = buildTree(preOrder, ps + 1, ps + index - is, inOrder, is, index - 1);
		root.right = buildTree(preOrder, ps + index - is + 1, pe, inOrder, index + 1, ie);
		
		return root;
	}
	
	
	public static void main(String[] args) {
		Node root = createBinaryTree();
		preOrder(root);
		System.out.println("");
		inOrder(root);
		System.out.println("");
		
		int[] preOrder = {0, 1, 3, 2};
		int[] inOrder = {3, 1, 0, 2};
		Node newRoot = buildTree(preOrder, inOrder);
		System.out.println("pre order: ");
		preOrder(newRoot);
		System.out.println("");
		System.out.println("in order: ");
		inOrder(newRoot);
	}
	

	private static void preOrder(Node root) {
		System.out.print(root.value + " ");
		if (root.left != null) {
			preOrder(root.left);
		}
		if (root.right != null) {
			preOrder(root.right);
		}
	}
	
	private static void inOrder(Node root) {
		if (root.left != null) {
			inOrder(root.left);
		}
		System.out.print(root.value + " ");
		if (root.right != null) {
			inOrder(root.right);
		}
	}
	
	private static Node createBinaryTree() {
        Node root = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        
        root.left = node1;
        root.right = node2;
        
        Node node3 = new Node(3);
        node1.left = node3;
        
        return root;
    }
	
}

 

参考:

构建二叉树:https://blog.csdn.net/derrantcm/article/details/45457557

上一篇:力扣--根据前序、中序和后序来重建二叉树


下一篇:c# – VB6变体类型到.NET类型