LeetCode Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:nseer erp 源码下载 编辑:程序博客网 时间:2024/06/06 03:56
Description:
Given inorder and postorder traversal of a tree, construct the binary tree.
Solution:
和前一道题目类似,不过这里的len表示的是当前根节点的右子树。
中序:(左子树)(根节点)(len长度的右子树)
后序:(左子树)(len长度的右子树)(根节点)
import java.util.*;public class Solution {int[] inorder;int[] postorder;int n;public TreeNode buildTree(int[] inorder, int[] postorder) {this.inorder = inorder;this.postorder = postorder;int n = inorder.length;return dfs(0, n - 1, 0, n - 1);}TreeNode dfs(int inStart, int inEnd, int postStart, int postEnd) {if (inStart > inEnd)return null;int inMiddle = inStart;for (int i = inStart; i <= inEnd; i++) {if (inorder[i] == postorder[postEnd]) {inMiddle = i;break;}}int len = inEnd - inMiddle;TreeNode root = new TreeNode(postorder[postEnd]);root.left = dfs(inStart, inMiddle - 1, postStart, postEnd - 1 - len);root.right = dfs(inMiddle + 1, inEnd, postEnd - len, postEnd - 1);return root;}}
0 0
- *(leetcode) Construct Binary Tree from Inorder and Postorder Traversal (tree)
- LeetCode[Tree]: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- leetcode 110: Construct Binary Tree from Inorder and Postorder Traversal
- 【leetcode】Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode-Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode - Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode] Construct Binary Tree from Inorder and Postorder Traversal
- 文字滚动
- HDU 1001
- iOS 一个带动画的等待指示器
- nginx lua调用redis和mongo
- 在一台用户PC主机上,子网掩码、默认网关的作用是什么?
- LeetCode Construct Binary Tree from Inorder and Postorder Traversal
- eclipse反编译插件----网上资料的坑爹系列
- git 初级基础
- HTTP 超文本传输协议
- leetCode 18.4Sum (4数字和) 解题思路和方法
- Myeclipse-查找类文件(Open Type)
- 倘若音乐(Android)
- sass基础
- nginx lua调用redis和mongo