首页 > 代码库 > 【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告
【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.
题意:根据二叉树先序遍历和中序遍历的结果,构造二叉树。跟 根据中序遍历和后序遍历结果构造二叉树 类似。
先序遍历:root - left - right,中序遍历:left - root - right。
不同的是,先序遍历的第一个元素就是根节点。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { int[] preorder; int[] inorder; public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder.length < 1 || inorder.length < 1) return null; this.preorder = preorder; this.inorder = inorder; return getRoot(0, inorder.length - 1, 0); } // sub-tree range form begin to end in inorder[] // rootpos refer the root postion in preorder[] public TreeNode getRoot(int begin, int end, int rootpos) { if (begin > end) return null; TreeNode root = new TreeNode(preorder[rootpos]); int i; for (i = begin; i <= end; i++) { if (inorder[i] == preorder[rootpos]) break; } // left part length: i - begin, right part length: end - i root.left = getRoot(begin, i - 1, rootpos + 1); root.right = getRoot(i + 1, end, rootpos + 1 + (i - begin)); return root; } }
【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。