本文主要是介绍LeetCode - construct-binary-tree-from-preorder-and-inorder-traversal,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题意:
根据前序序列和中序序列来构造二叉树
可以假设二叉树中没有重复的数
解题思路:
中序和后序构造二叉树 和这题思路差不多
从前序序列获取根结点,也就是第一个结点就是根结点
然后在中序序列中找到这个结点,以该结点将左右部分划分为左右子树
然后递归连接左右结点,最终构造成二叉树
代码:
public TreeNode buildTree(int[] preorder, int[] inorder) {if(preorder.length <= 0 || inorder.length <= 0) {return null;}return getTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);}public TreeNode getTree(int[] preorder, int pres, int pree, int[] inorder, int ins, int ine) {if(pres > pree || ins > ine) {return null;}TreeNode root = new TreeNode(preorder[pres]);for(int i = ins ;i <= ine ;i++) {if(inorder[i] == preorder[pres]) {root.left = getTree(preorder,pres+1,i-ins+pres,inorder,ins,i-1);root.right = getTree(preorder,i-ins+pres+1,pree,inorder,i+1,ine);}}return root;}
这篇关于LeetCode - construct-binary-tree-from-preorder-and-inorder-traversal的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!