fork download
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  * int val;
  5.  * TreeNode left;
  6.  * TreeNode right;
  7.  * TreeNode() {}
  8.  * TreeNode(int val) { this.val = val; }
  9.  * TreeNode(int val, TreeNode left, TreeNode right) {
  10.  * this.val = val;
  11.  * this.left = left;
  12.  * this.right = right;
  13.  * }
  14.  * }
  15.  */
  16. class Solution {
  17. public TreeNode buildTree(int[] preorder, int[] inorder) {
  18.  
  19.  
  20. return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
  21. }
  22.  
  23.  
  24. public TreeNode buildTree(int[] preorder, int prS, int prE, int[] inorder, int inS, int inE) {
  25.  
  26. if (inS > inE)
  27. return null;
  28.  
  29. int rootVal = preorder[prS];
  30.  
  31. int rootIdx = -1;
  32.  
  33. for (int i = inS; i <= inE; i++) {
  34.  
  35. if (inorder[i] == rootVal) {
  36.  
  37. rootIdx = i;
  38. break;
  39. }
  40. }
  41.  
  42.  
  43. TreeNode root = new TreeNode(rootVal);
  44.  
  45.  
  46. int inLS = inS;
  47. int inLE = rootIdx - 1;
  48.  
  49. int prLS = prS + 1;
  50. int prLE = (inLE - inLS + prLS);
  51.  
  52. int prRS = prLE + 1;
  53. int prRE = prE;
  54.  
  55. int inRS = rootIdx + 1;
  56. int inRE = inE;
  57.  
  58.  
  59. root.left = buildTree(preorder, prLS, prLE, inorder, inLS, inLE);
  60. root.right = buildTree(preorder, prRS, prRE, inorder, inRS, inRE);
  61.  
  62. return root;
  63. }
  64. }
Compilation error #stdin compilation error #stdout 0s 0KB
stdin
Standard input is empty
compilation info
Main.java:17: error: cannot find symbol
    public TreeNode buildTree(int[] preorder, int[] inorder) {
           ^
  symbol:   class TreeNode
  location: class Solution
Main.java:24: error: cannot find symbol
    public TreeNode buildTree(int[] preorder, int prS, int prE, int[] inorder, int inS, int inE) {
           ^
  symbol:   class TreeNode
  location: class Solution
Main.java:43: error: cannot find symbol
        TreeNode root = new TreeNode(rootVal);
        ^
  symbol:   class TreeNode
  location: class Solution
Main.java:43: error: cannot find symbol
        TreeNode root = new TreeNode(rootVal);
                            ^
  symbol:   class TreeNode
  location: class Solution
4 errors
stdout
Standard output is empty