根據先序遍歷和中續遍歷重構二叉樹

今天在牛客網上遇到這樣一道題,題目內容如下:

題目描述:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。

題目的意思是根據一棵二叉樹的先序和後續序列重構二叉樹。
階梯思路是:
(1)首先先序中的第一個元素一定是二叉樹的根節點。根據這個根節點找到在中序中的位置,那麼這一位置左邊的元素全部是二叉樹的左孩子,這一節點的所有右邊節點全部是二叉樹的右孩子。
(2)其次構造右子樹和左子樹。構造思路是:從先序和中序中找到左子樹和右子樹的先序和中序序列,然後遞歸構造,直至所有節點使用完。即得到重構的二叉樹。

參考代碼如下:

//節點的數據結構
class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x) {
		val = x;
	}
}
public class Main {
	public static TreeNode reConstructBinaryTree(int[] pre, int[] in) {
		if(pre.length == 0 || in.length == 0 || pre.length != in.length){
			return null;
		}
		//在中序中找到根節點所在的位置,中序中該位置左邊的爲左子樹,右邊的爲右子樹
		int i = 0;
		while(pre[0] != in[i]){
			i++;
		}
		//創建一棵樹
		TreeNode root = new TreeNode(pre[0]);
		//左子樹中序爲
		int inLeftTree[] = new int[i];
		for(int k = 0; k < i ; k++){
			inLeftTree[k] = in[k];
		}
		//右子樹中序爲
		int inRightTree[] = new int[in.length - i -1];
		for(int k = i + 1; k < in.length; k++){
			inRightTree[k - i -1] = in[k];
		}
		//左子樹的先序爲
		int preLeft[] = new int[i];
		for(int k = 0; k < i; k++){
			preLeft[k] = pre[k + 1];
		}
		//右子樹的先序爲
		int preRight[] = new int[pre.length - i - 1];
		for(int k = i + 1; k < pre.length; k++){
			preRight[k -i -1] = pre[k];
		}
		//遞歸構造左右子樹
		root.left = reConstructBinaryTree(preLeft, inLeftTree);
		root.right = reConstructBinaryTree(preRight, inRightTree);
		return root;
	}

	public static void main(String[] args) {
		int[] a = { 1, 2, 4, 7, 3, 5, 6, 8 };
		int[] b = { 4, 7, 2, 1, 5, 3, 8, 6 };
		TreeNode root = reConstructBinaryTree(a, b);
		
		//後續遍歷二叉樹
		lastList(root);
	}
	//後續遍歷這棵二叉樹 以驗證重構的是否正確
	private static void lastList(TreeNode root) {
		if(root == null){
			return;
		}
		last(root.left);
		last(root.right);
		System.out.print(root.val + " ");
	}
}

轉發連接:http://blog.csdn.net/a469142780/article/details/76222341

這二叉樹的實際結構如下圖:
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章