本文主要是介绍Java面试:重建二叉树题目,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
解答:
public static void main(String[] args) {//前序遍历数int [] preNode ={1,2,4,7,3,5,6,8};//中序遍历数int [] infixNode ={4,7,2,1,5,3,8,6};TreeNode treeNode = rebuildTree(preNode, infixNode);System.out.println(treeNode);}private static TreeNode rebuildTree(int [] preNode,int [] infixNode){if(null == preNode|| null == infixNode || preNode.length ==0 ||infixNode.length ==0 || preNode.length != infixNode.length){return null;}TreeNode treeNode = new TreeNode(preNode[0]);for(int i =0 ; i < preNode.length ; i++){treeNode.leftNode= rebuildTree(Arrays.copyOfRange(preNode,1,i+1),Arrays.copyOfRange(infixNode,0,i));treeNode.rightNode =rebuildTree(Arrays.copyOfRange(preNode,i+1,preNode.length),Arrays.copyOfRange(infixNode,i+1,infixNode.length));}return treeNode;}
TreeNode类如下:
public class TreeNode {private int value;TreeNode leftNode;TreeNode rightNode;public TreeNode(int value) {this.value = value;}@Overridepublic String toString() {return "TreeNode{" +"value=" + value +", leftNode=" + leftNode +", rightNode=" + rightNode +'}';}
}
这篇关于Java面试:重建二叉树题目的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!