rebuild binary tree

Problem Description

在这里插入图片描述

analysis

  • The key to this problem is to know what we need to know for recursion. For example, we need to know the position of the root node of the left subtree in the original preorder sequence is pre_root + 1, and then we need to know the position of the left subtree in the original preorder sequence, which can be obtained according to the traversal rule of the binary tree.So to summarize, to locate the left subtree, we need to know three index positions, and the same goes for the right subtree.
  • What’s a little harder to understand here is the index of the root node of the right subtree in the preorder sequence: the index of the root node + the length of the left subtree +1

solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

import java.util.*;

class TreeNode{
	public int key;
	public TreeNode left;
	public TreeNode right;
	TreeNode(int x) { key = x; }
	public void traversal(TreeNode t){
		if(t != null){
			traversal(t.left);
			System.out.println(t.key);
			traversal(t.right);
		}
	}
}

class Solution{
    HashMap<Integer, Integer> dic = new HashMap<>();
    int[] po;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        po = preorder;
        for(int i = 0; i < inorder.length; i++) 
            dic.put(inorder[i], i); //put inorder into map
        return recur(0, 0, inorder.length - 1);
    }
    TreeNode recur(int pre_root, int in_left, int in_right) {
        if(in_left > in_right) return null;
        TreeNode root = new TreeNode(po[pre_root]);
        int i = dic.get(po[pre_root]);
        root.left = recur(pre_root + 1, in_left, i - 1);
        root.right = recur(pre_root + i - in_left + 1, i + 1, in_right);
        return root;
    }

    public static void main(String[] args) {
		Solution s = new Solution();
		int[] pre = {3,9,20,15,7};
		int[] in = {9,3,15,20,7};
		TreeNode t = s.buildTree(pre, in);
		t.traversal(t);//use inorder traversal to testify the result.
	}
}
//this solution is extracted from :
//https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-di-gui-fa-qin/
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值