Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

开始还想着有重复怎么办,后来发现题目给了没有重复数字,如果有重复数字那树可能不唯一,但是假如只有一两个重复数字树还是可能唯一的,那样的话深搜应该就可以了。

递归就可以了

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildBinary(int[] preorder, int low1, int high1, int[] inorder, int low2, int high2){
        if(low1 == high1){
            return new TreeNode(preorder[low1]);
        }
        if(low1 > high1){
            return null;
        }
        TreeNode root = new TreeNode(preorder[low1]);
        int inorder_root_idx;
        for(inorder_root_idx=low2; inorder_root_idx <= high2; ++inorder_root_idx){
            if(root.val == inorder[inorder_root_idx]){
                break;
            }
        }
        TreeNode left = buildBinary(preorder, low1+1, low1+inorder_root_idx-low2, inorder, low2, inorder_root_idx-1);
        TreeNode right = buildBinary(preorder,low1+inorder_root_idx-low2+1,high1,inorder,inorder_root_idx+1,high2);
        root.left = left;
        root.right = right;
        return root;
    }
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode root;
        if(preorder.length == 0){
            return null;
        }
        root = buildBinary(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
        return root;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值