1. 程式人生 > 實用技巧 >4、重建二叉樹

4、重建二叉樹

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

=============Python=============

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution: # 返回構造的TreeNode根節點 def reConstructBinaryTree(self, pre, tin): # write code here if not tin: return tmp = pre.pop(0) root = TreeNode(tmp) root.left = self.reConstructBinaryTree(pre, tin[0:tin.index(tmp)]) root.right = self.reConstructBinaryTree(pre, tin[tin.index(tmp)+1:])
return root

===============Java=================

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] 
in) { if (pre == null || pre.length == 0 || in == null || in.length == 0 || pre.length != in.length) { return null; } return reConstruct(pre, in, 0, pre.length - 1, 0, in.length - 1); } public TreeNode reConstruct(int[] pre, int[] in, int preStart, int preEnd, int inStart, int inEnd) { if (preStart > preEnd || inStart > inEnd) { return null; } TreeNode head = new TreeNode(pre[preStart]); int inPos = 0; while (in[inPos] != pre[preStart]) { inPos++; } int minus = inPos - inStart; head.left = reConstruct(pre, in, preStart + 1, preStart + minus, inStart, inPos - 1); head.right = reConstruct(pre, in, preStart + minus + 1, preEnd, inPos + 1, inEnd); return head; } }