[leetcode]106. Construct Binary Tree from Inorder and Postorder Traversal@Java结题报告

来源:互联网 发布:sql触发器实例 old 编辑:程序博客网 时间:2024/06/06 01:31

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/


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

Note:
You may assume that duplicates do not exist in the tree.





package go.jacob.day807;/** * 106. Construct Binary Tree from Inorder and Postorder Traversal *  * @author Jacob * */public class Demo1 {public TreeNode buildTree(int[] inorder, int[] postorder) {if (inorder == null)return null;return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);}private TreeNode buildTree(int[] inorder, int inLeft, int inRight, int[] postorder, int postLeft, int postRight) {if (inLeft > inRight)return null;TreeNode root = new TreeNode(postorder[postRight]);// 只有一个节点,返回rootif (inLeft == inRight)return root;int rootNum = 0;for (int i = inLeft; i <= inRight; i++) {if (inorder[i] == postorder[postRight]) {rootNum = i;break;}}int leftLength = rootNum - inLeft;//递归左子树和右子树root.left = buildTree(inorder, inLeft, inLeft + leftLength - 1, postorder, postLeft, postLeft + leftLength - 1);root.right = buildTree(inorder, inLeft + leftLength + 1, inRight, postorder, postLeft + leftLength,postRight - 1);return root;}}


阅读全文
0 0