LeetCode-----Construct Binary Tree from Inorder and Postorder Traversal
程序员文章站
2022-03-07 23:50:01
...
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.
从中序和后序遍历的结果来重建原二叉树,我们知道中序的遍历顺序是左-根-右,后序的顺序是左-右-根,对于这种树的重建一般都是采用递归来做,由于后序的顺序的最后一个肯定是根,所以原二叉树的根节点可以知道,题目中给了一个很关键的条件就是树中没有相同元素,有了这个条件我们就可以在中序遍历中也定位出根节点的位置,并以根节点的位置将中序遍历拆分为左右两个部分,分别对其递归调用原函数。
实例代码如下:
package com.zhumq.lianxi;
public class PostorderAndInorder {
//定义TreeNode
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public TreeNode buildTree(int[] postorder, int[] inorder) {
return buildTree(postorder, 0, postorder.length-1,inorder, 0, inorder.length-1);
}
public TreeNode buildTree(int[] postorder, int pleft, int pright,int[] inorder, int ileft, int iright) {
if (ileft > iright || pleft > pright) return null;
//初始根节点为后序的最后一个节点。
TreeNode cur = new TreeNode(postorder[pright]);
//用i定位到中序根节点的位置。
int i = 0;
for (i = ileft; i < inorder.length; ++i) {
if (inorder[i] == postorder[pright]) break;
}
//分解成左右两个子问题,分别返回左右子树的根节点。
cur.left = buildTree(inorder, ileft, i - 1, postorder, pleft, pleft + i - ileft - 1);
cur.right = buildTree(inorder, i + 1, iright, postorder, pleft + i - ileft, pright - 1);
return cur;
}
}
我们下面来看一个例子, 某一二叉树的中序和后序遍历分别为:
做完这道题后,大多人可能会有个疑问,怎么没有由先序和后序遍历建立二叉树呢,这是因为先序和后序遍历不能唯一的确定一个二叉树,比如下面五棵树:
从上面我们可以看出,对于先序遍历都为1 2 3的五棵二叉树,它们的中序遍历都不相同,而它们的后序遍历却有相同的,所以只有和中序遍历一起才能唯一的确定一棵二叉树。
推荐阅读
-
Binary Tree Postorder Traversal
-
LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal
-
LeetCode: 105. Construct Binary Tree from Preorder and Inorder Traversal
-
leetcode 随笔 Construct Binary Tree from Preorder and Inorder Traversal
-
105. Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
Construct Binary Tree from Preorder and Inorder Traversal
-
Given a binary tree, return the postorder traversal of its nodes' values.非递归后续遍历
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
leetcode: binary-tree-postorder-traversal:后序遍历二叉树