Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:日本买mac口红便宜吗 编辑:程序博客网 时间:2024/06/09 18:20

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

public TreeNode buildTree(int[] preorder, int[] inorder) {return helper(0, 0, inorder.length - 1, preorder, inorder);}public TreeNode helper(int preStart, int inStart, int inEnd, int[] preorder, int[] inorder) {if (preStart > preorder.length - 1 || inStart > inEnd) {return null;}TreeNode root = new TreeNode(preorder[preStart]);int inIndex = 0; // Index of current root in inorderfor (int i = inStart; i <= inEnd; i++) {if (inorder[i] == root.val) {inIndex = i;}}root.left = helper(preStart + 1, inStart, inIndex - 1, preorder, inorder);root.right = helper(preStart + inIndex - inStart + 1, inIndex + 1, inEnd, preorder, inorder);return root;}


0 0
原创粉丝点击