美文网首页
重建二叉树

重建二叉树

作者: 上杉丶零 | 来源:发表于2019-12-14 02:30 被阅读0次
    package leetcode.剑指Offer.重建二叉树;
    
    import java.util.Arrays;
    
    public class LeetCode {
        public static void main(String[] args) {
            System.out.println(new Solution().buildTree(new int[] {3, 9, 20, 15, 7}, new int[] {9, 3, 15, 20, 7}));
        }
    }
    
    class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if (preorder == null || inorder == null || preorder.length == 0 || preorder.length != inorder.length) {
                return null;
            }
    
            TreeNode rootTreeNode = new TreeNode(preorder[0]);
    
            if (preorder.length == 1) {
                return rootTreeNode;
            }
    
            int rootValue = preorder[0];
            int rootIndex = 0;
    
            for (int i = 0; i < inorder.length; i++) {
                if (inorder[i] == rootValue) {
                    rootIndex = i;
                    break;
                }
            }
    
            rootTreeNode.left = buildTree(Arrays.copyOfRange(preorder, 1, rootIndex + 1), Arrays.copyOfRange(inorder, 0, rootIndex));
            rootTreeNode.right = buildTree(Arrays.copyOfRange(preorder, rootIndex + 1, preorder.length), Arrays.copyOfRange(inorder, rootIndex + 1, inorder.length));
            return rootTreeNode;
        }
    }
    
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
    
        TreeNode(int x) {
            val = x;
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:重建二叉树

          本文链接:https://www.haomeiwen.com/subject/zjtcnctx.html