Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:淘宝店铺被永久查封 编辑:程序博客网 时间:2024/06/11 08:15

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;    }}


0 0
原创粉丝点击