construct-binary-tree-from-inorder-and-postorder-traversal
来源:互联网 发布:白城广逸网络具体位置 编辑:程序博客网 时间:2024/06/11 06:28
1、来源: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.
2、思路,通过中序和后序来构建树:
- 后序的最后一个元素为当前根结点root;
- 在中序中,这个root左边为左子树,右边为右子树,递归就好了
3、代码:
public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder == null || inorder.length == 0) return null; TreeNode root = biuld(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); return root; } private TreeNode biuld( int[] inorder, int start1, int end1, int[] postorder, int start2, int end2) { int root_val = postorder[end2]; TreeNode root = new TreeNode(root_val); int i; for(i = start1; i < end1; i++){ if(root_val == inorder[i]) break; } if(i - start1 > 0 ){ root.left = biuld( inorder, start1, i - 1, postorder, start2, start2 + i - 1 - start1); } if(end1 - i > 0 ){ root.right = biuld( inorder, i + 1, end1, postorder, end2 - end1 + i, end2 - 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
- 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
- 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
- [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
- Construct Binary Tree from Inorder and Postorder Traversal
- poj-1007 DNA sorting
- LQB-2
- Java中ArrayList和LinkedList区别
- HDU 1875:畅通工程再续
- 简单说 CSS滤镜 filter属性
- construct-binary-tree-from-inorder-and-postorder-traversal
- 笔记10
- 丑数
- 第八周项目二—建立链串的算法库
- SpringMVC中的controller
- Web安全,常见攻击防范
- 程序员必备之沟通的艺术
- leetcode 219. Contains Duplicate II 217. Contains Duplicate
- 【Java基础18_1】Map集合