脚本宝典收集整理的这篇文章主要介绍了NC_12_reConstructBinaryTree,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
package org.example.interview.practice; /** * @author xianzhe.ma * @date 2021/9/7 */ public class NC_12_reConstructBinaryTree { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { return dfs(0, 0, in.length - 1, pre, in); } public TreeNode dfs(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 index = 0; //找到当前节点root在中序遍历中的位置,然后再把数组分两半 for (int i = inStart; i <= inEnd; i++) { if (inorder[i] == root.val) { index = i; break; } } root.left = dfs(preStart + 1, inStart, index - 1, preorder, inorder); root.right = dfs(preStart + index - inStart + 1, index + 1, inEnd, preorder, inorder); return root; } public static class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } }
以上是脚本宝典为你收集整理的NC_12_reConstructBinaryTree全部内容,希望文章能够帮你解决NC_12_reConstructBinaryTree所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。