标签:cti || base dtree ini ons class uil res
Construct Binary Tree from Preorder and Inorder Traversal /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder == null || inorder == null || preorder.length == 0 || inorder.length == 0 || preorder.length != inorder.length){ return null; } return construct(preorder, inorder, 0, 0, inorder.length - 1); } private TreeNode construct(int[] preorder, int[] inorder, int preStart, int inStart, int inEnd){ // BASE CASE if(preStart > preorder.length || inStart > inEnd) return null; // recursion + induction rule // find the size of left subtree int i = inStart; while (i <= inEnd){ if(inorder[i] == preorder[preStart]){ break; } i++; } // root TreeNode root = new TreeNode(preorder[preStart]); root.left = construct(preorder, inorder, preStart + 1, inStart, i -1); root.right = construct(preorder, inorder, preStart + (i - inStart + 1), i + 1, inEnd); return root; } }
Construct Binary Tree from Preorder and Inorder Traversal
标签:cti || base dtree ini ons class uil res
原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550674.html