首页 > 代码库 > LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Hide Tags
Tree Array Depth-first SearchSOLUTION 1:
使用递归的思想,先找到根节点(它就是post order最后一个),然后再在inorder中找到它,以确定左子树的node个数。
然后分别确定左子树右子树的左右边界
例子:
{4, 5, 2, 7, 8, 1, 3}这树的
inorder: 7 5 8 | 4 | 1 2 3
post: 7 8 5 | 1 3 2 | 4
以上我们可以看到左右子树的划分关系。
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */10 public class Solution {11 public TreeNode buildTree(int[] inorder, int[] postorder) {12 if (inorder == null || postorder == null) {13 return null;14 }15 16 return dfs(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);17 }18 19 public TreeNode dfs(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR) {20 if (inL > inR) {21 return null;22 }23 24 // create the root node.25 TreeNode root = new TreeNode(postorder[postR]);26 27 // find the position of the root node in the inorder traversal.28 int pos = 0;29 for (; pos <= inR; pos++) {30 if (inorder[pos] == postorder[postR]) {31 break;32 }33 }34 35 int leftNum = pos - inL;36 37 root.left = dfs(inorder, postorder, inL, pos - 1, postL, postL + leftNum - 1);38 root.right = dfs(inorder, postorder, pos + 1, inR, postL + leftNum, postR - 1);39 40 return root;41 }42 }
代码: https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/BuildTree2.java
LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。