package swordOffre.gaopengyu; public class BuildBST7 { static int[] preOrder = new int[]{1, 2, 4, 7, 3, 5, 6, 8}; static int[] inOrder = new int[]{4, 7, 2, 1, 5, 3, 8, 6}; public static void main(String[] args) { TreeNode root = constuctBST(0, preOrder.length - 1, 0, inOrder.length - 1, new TreeNode(0, null, null)); afterTravers(root); } public static TreeNode constuctBST(int preStart, int preEnd, int inStart, int inEnd, TreeNode node) { if (preEnd - preStart < 0 || inEnd - inStart < 0 || preEnd - preStart != inEnd - inStart) { return null; } node.val = preOrder[preStart]; if (preEnd - preStart == 0 && inEnd - inStart == 0) { return node; } int root = findRootInInOrder(inStart, inEnd, node); if (root == -1) { return null; } node.left = constuctBST(preStart + 1, preStart+root-inStart,inStart,root-1,new TreeNode(0,null,null) ); node.right = constuctBST(preStart+root-inStart+1,preEnd,root+1,inEnd,new TreeNode(0,null,null)); return node; } public static int findRootInInOrder(int inStart, int inEnd, TreeNode node) { for (int i = inStart; i <= inEnd; i++) { if (node.val == inOrder[i]) { return i; } } return -1; } public static void afterTravers(TreeNode node) { if (node==null){ return; } afterTravers(node.left); afterTravers(node.right); System.out.print(node.val+"->"); } }
重建二叉树7
最新推荐文章于 2022-03-07 18:59:14 发布