construct-binary-tree-from-preorder-and-inorder-traversal
Posted Adding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.
package com.cn.cya.constructbinarytreefrompreorderandinordertraversal; class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder==null||preorder.length==0||inorder==null||inorder.length==0||preorder.length!=inorder.length) return null; return build_Tree(preorder,0,preorder.length-1,inorder,0,inorder.length-1); } public TreeNode buildTree(int[] preorder,int prestar,int preend,int[] inorder,int instar,int inend){ if(prestar>preend||instar>inend)return null; int root_val=preorder[prestar]; TreeNode root=new TreeNode(root_val); int index=instar;//preorder中第一个元素在中序遍历中的位置 for (;index < inend&&inorder[index]!=root_val; index++) { } root.left=buildTree(preorder,prestar+1, prestar+index-instar, inorder,instar,index-1); root.right=buildTree(preorder,prestar+index-instar+1, preend, inorder,index+1,inend); return root; } }
以上是关于construct-binary-tree-from-preorder-and-inorder-traversal的主要内容,如果未能解决你的问题,请参考以下文章