[LeetCode]Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:cimatrone11编程 编辑:程序博客网 时间:2024/04/29 16:54

题目描述

Given preorder and inorder traversal of a tree, construct the binary tree.

根据二叉树先序和中序遍历结果构造二叉树。

解题思路


递归:
  1. 找到并建立根节点;
  2. 根据根节点位置确定左右子树的元素,并分别构造左右子树;
  3. 重复1、2步骤


代码


/** * 根据二叉树先序和中序遍历结果构造二叉树 * @param preorder * @param inorder * @return */public static TreeNode buildTree(int[] preorder, int[] inorder) {if (preorder == null || inorder == null || preorder.length == 0|| inorder.length == 0)return null;int rootValue = preorder[0];int[] leftP, leftI, rightP, rightI;TreeNode root = new TreeNode(rootValue);int i;//找到中序遍历中根节点的位置for (i = 0; i < inorder.length; i++) {if (inorder[i] == rootValue) {break;}}if (i == 0 && i != inorder.length - 1) {//没有左子树root.left = null;rightP = Arrays.copyOfRange(preorder, i + 1, preorder.length);rightI = Arrays.copyOfRange(inorder, i + 1, inorder.length);root.right = buildTree(rightP, rightI);} else if (i == inorder.length - 1 && i != 0) {//没有右子树root.right = null;leftP = Arrays.copyOfRange(preorder, 1, i + 1);leftI = Arrays.copyOfRange(inorder, 0, i);root.left = buildTree(leftP, leftI);} else if (i == 0 && i == inorder.length - 1) {//没有左子树和右子树,为叶节点root.left = null;root.right = null;} else {leftP = Arrays.copyOfRange(preorder, 1, i + 1);leftI = Arrays.copyOfRange(inorder, 0, i);rightP = Arrays.copyOfRange(preorder, i + 1, preorder.length);rightI = Arrays.copyOfRange(inorder, i + 1, inorder.length);root.left = buildTree(leftP, leftI);root.right = buildTree(rightP, rightI);}return root;}


0 0
原创粉丝点击