106. Construct Binary Tree from Inorder and Postorder Traversal
Posted 热带雨林
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了106. 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.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / \\ 9 20 / \\ 15 7
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { int length = inorder.length; return buildTree(inorder, 0, length - 1, postorder, 0, length - 1); } public TreeNode buildTree(int[] inorder, int instart, int inend, int[] postorder, int postart, int postend){ if(instart > inend || postart > postend) return null; int rootval = postorder[postend]; int rootind = 0; for(int i = instart; i <= inend; i++){ if(rootval == inorder[i]){ rootind = i; break; } } int len = rootind - instart; TreeNode root = new TreeNode(rootval); root.left = buildTree(inorder, instart, rootind-1, postorder, postart, postart + len - 1); root.right = buildTree(inorder, rootind + 1, inend, postorder, postart + len, postend-1 ); return root; } }
以上是关于106. Construct Binary Tree from Inorder and Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
106. Construct Binary Tree from Inorder and Postorder Traversal
[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal