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

2023.10.21

leetcode 105. 从前序与中序遍历序列构造二叉树_第1张图片

        本题需要根据前序遍历序列和中序遍历序列来构造出一颗二叉树。类似于从中序与后序遍历序列构造二叉树 。使用递归, java代码如下:

/**
 * 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) {
        if(inorder.length == 0) return null;
        int rootValue = preorder[0];
        TreeNode root = new TreeNode(rootValue);
        if(inorder.length == 1) return root;
        //找到中序遍历的切割点
        int seg = 0;
        for(int i=0; i

 

 

你可能感兴趣的:(leetcode专栏,leetcode,数据结构,算法,java)