快捷搜索: 王者荣耀 脱发

根据前序遍历和中序遍历树构造二叉树

一、题目描述

根据前序遍历和中序遍历树构造二叉树.

注意事项:你可以假设树中不存在相同数值的节点

样例 给出中序遍历:[1,2,3]和前序遍历:[2,1,3]. 返回如下的树:

2
 / 
1   3

二、解题思路

1、首先根据前序遍历序列的第一个数字创建根结点(前序遍历序列的第一个数字就是根结点) 2、然后在中序遍历序列中找到根结点所在的位置,这样就能确定左、右子树结点的数量,这样也就分别找到了左、右子树的前序遍历序列和中序遍历序列。 3、然后用递归的方法去构建左、右子树,直到叶子结点。

三、代码实现

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
          
   
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    //找到根节点的位置
    private int findPosition(int[] array, int start, int end, int key) {
        for (int i = start; i <= end; i++) {
            if (array[i] == key) {
                return i;
            }
        }
        return -1;
    }
    private TreeNode myBuildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
        if (inStart > inEnd) {
            return null;
        }
        //前序遍历序列的第一个数字就是根结点,创建根结点root
        TreeNode root = new TreeNode(preorder[preStart]);
        //在中序遍历序列中找到根结点的位置
        int position = findPosition(inorder, inStart, inEnd, preorder[preStart]);
        //构建左子树
        root.left = myBuildTree(preorder, preStart + 1, preStart + (position - inStart), inorder, inStart, position - 1);
        //构建右子树
        root.right = myBuildTree(preorder, preStart + (position - inStart) + 1, preEnd, inorder, position + 1, inEnd);
        return root;
    }     
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder.length != inorder.length) {
         
  //前序遍历序列与中序遍历序列长度不等
            return null;
        }
        return myBuildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }
}
经验分享 程序员 微信小程序 职场和发展