Leetcode 105: Construct Binary Tree from Preorder and Inorder Traversal

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

Note:
You may assume that duplicates do not exist in the tree.

 

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left;
 6  *     public TreeNode right;
 7  *     public TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode BuildTree(int[] preorder, int[] inorder) {
12         if (preorder.Length == 0) return null;
13         
14         return DFS(preorder, 0, preorder.Length - 1, inorder, 0, inorder.Length - 1);
15     }
16     
17     private TreeNode DFS(int[] preorder, int pStart, int pEnd, int[] inorder, int iStart, int iEnd)
18     {
19         if (pStart > pEnd) return null;
20         if (pStart == pEnd) return new TreeNode(preorder[pStart]);
21         
22         var root = new TreeNode(preorder[pStart]);
23         
24         int i = iStart;
25         for (; i <= iEnd; i++)
26         {
27             if (inorder[i] == preorder[pStart]) break;
28         }
29         
30         root.left = DFS(preorder, pStart + 1, pStart + i - iStart, inorder, iStart, i - 1);
31         root.right = DFS(preorder, pStart + i - iStart + 1, pEnd, inorder, i + 1, iEnd);
32         
33         return root;
34     }
35 }

 

posted @ 2017-11-20 02:32  逸朵  阅读(95)  评论(0)    收藏  举报