105. 从前序与中序遍历序列构造二叉树 + 树遍历

105. 从前序与中序遍历序列构造二叉树

LeetCode_105

题目描述

解法描述

  1. 题目主要考察的是我们对二叉树三种遍历的熟悉程度。
  2. 构建二叉树的时候首先可以根据前序遍历找出根节点,接着根据根节点在中序遍历找到划分左右子树的分界点。
  3. 然后新建一个树结点,递归构建其左右子树。

代码描述

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }
    public TreeNode build(int[] preorder, int pl, int pr, int[] inorder, int il, int ir){
        if(pl > pr)
            return null;
        int head = preorder[pl];
        int i = il;
        for(i = il; i<= ir; i++){
            if(inorder[i] == head)
                break;
        }
        int lchildlen = i - il;
        int rchildlen = ir - i;
        TreeNode now = new TreeNode(head);
        now.left = build(preorder, pl + 1, pl + lchildlen, inorder, il, i-1);
        now.right = build(preorder, pl + lchildlen + 1, pr, inorder, i + 1, ir);
        return now;
    }
}
posted @ 2021-03-18 09:58  Garrett_Wale  阅读(59)  评论(0编辑  收藏  举报