【Java概念學習】--陣列的初始化
阿新 • • 發佈:2022-05-04
package leetcode; import java.util.HashMap; public class demo_105 { public TreeNode buildTree(int[] preorder, int[] inorder) { HashMap<Integer, Integer> map=new HashMap<Integer, Integer>(); //保留節點在中序遍歷中的位置 for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); }return myBuildTree(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1, map); } public TreeNode myBuildTree(int[] preorder,int[] inorder,int preleft,int preright,int inleft,int inright,HashMap<Integer, Integer> map ) { if(preleft>preright) { return null; } //先序遍歷中根節點的位置 int preroot=preleft; //中序遍歷中根節點的位置 int inroot=map.get(preorder[preroot]); int lefttree=inroot-inleft; //創建出根節點 TreeNode root=new TreeNode(preorder[preroot]); //創建出左子樹 root.left=myBuildTree(preorder, inorder, preleft+1, preleft+lefttree, inleft, inroot-1, map);//創建出右子樹 root.right=myBuildTree(preorder, inorder, preleft+lefttree+1 , preright, inroot+1 ,inright, map); return root; } }