【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 根據先序序列和中序序列恢復二叉樹

HIT_微笑前進發表於2015-03-28

題目:Construct Binary Tree from Preorder and Inorder Traversal

<span style="font-size:18px;">/**LeetCode 
 * 題意:給定一個二叉樹的先序遍歷和中序遍歷的序列,重建二叉樹
 * 思路:先序遍歷的第一個節點是父節點,中序遍歷從第一個節點到父節點的都是父節點的左子樹,父節點後面的都是父節點的右子樹
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
package javaTrain;

public class Train20 {
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		int n = preorder.length;
		if(n == 0) return null;
		int m = 0;
		int num = preorder[0];
		boolean tag = true;
		for(int i = 0;i < n;i++){ 
			if(inorder[i] == num)
				break;
			m++;
		}
		int[] leftPre = new int[m];
		int[] leftIn = new int[m];
		int[] rightPre = new int[m-n-1];
		int[] rightIn = new int[m-n-1];
		for(int j = 0;j < n;j++){
			if(j == num-1) tag = false;
			if(tag){
				leftIn[j] = inorder[j];
				leftPre[j] = preorder[j+1];
			}
			else{
				rightIn[j-num-1] = inorder[j];
				rightPre[j] = preorder[j+1];
			}
		}
		TreeNode root = new TreeNode(num);
		root.left = buildTree(leftPre,leftIn);
		root.right = buildTree(rightPre,rightIn);
		return root;
    }
}
</span>


相關文章