本文主要是介绍【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 根据先序序列和中序序列恢复二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:Construct Binary Tree from Preorder and Inorder Traversal
<span style="font-size:18px;">/**LeetCode * 题意:给定一个二叉树的先序遍历和中序遍历的序列,重建二叉树* 思路:先序遍历的第一个节点是父节点,中序遍历从第一个节点到父节点的都是父节点的左子树,父节点后面的都是父节点的右子树* Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
package javaTrain;public class Train20 {public TreeNode buildTree(int[] preorder, int[] inorder) {int n = preorder.length;if(n == 0) return null;int m = 0;int num = preorder[0];boolean tag = true;for(int i = 0;i < n;i++){ if(inorder[i] == num)break;m++;}int[] leftPre = new int[m];int[] leftIn = new int[m];int[] rightPre = new int[m-n-1];int[] rightIn = new int[m-n-1];for(int j = 0;j < n;j++){if(j == num-1) tag = false;if(tag){leftIn[j] = inorder[j];leftPre[j] = preorder[j+1];}else{rightIn[j-num-1] = inorder[j];rightPre[j] = preorder[j+1];}}TreeNode root = new TreeNode(num);root.left = buildTree(leftPre,leftIn);root.right = buildTree(rightPre,rightIn);return root;}
}
</span>
这篇关于【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 根据先序序列和中序序列恢复二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!