leetcode地址:从前序与中序遍历序列构造二叉树
给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
示例 2:
输入: preorder = [-1], inorder = [-1]
输出: [-1]
提示:
1 <= preorder.length <= 3000
inorder.length == preorder.length
-3000 <= preorder[i], inorder[i] <= 3000
preorder 和 inorder 均 无重复 元素
inorder 均出现在 preorder
preorder 保证 为二叉树的前序遍历序列
inorder 保证 为二叉树的中序遍历序列
实现思路
先序遍历(Preorder):根节点 -> 左子树 -> 右子树
中序遍历(Inorder):左子树 -> 根节点 -> 右子树
通过给定的先序遍历和中序遍历数组,我们可以确定二叉树的根节点以及左右子树的范围。具体步骤如下:
步骤1:先序遍历的第一个元素是根节点的值。
步骤2:在中序遍历中找到根节点的位置,其左侧为左子树的中序遍历,右侧为右子树的中序遍历。
步骤3:根据步骤2中左右子树的大小,可以在先序遍历中确定左子树和右子树的先序遍历。
递归地应用以上步骤,即可构造整棵二叉树。
代码实现
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(preorder, inorder):
if not preorder or not inorder:
return None
root_val = preorder[0]
root = TreeNode(root_val)
idx = inorder.index(root_val)
root.left = buildTree(preorder[1:idx + 1], inorder[:idx])
root.right = buildTree(preorder[idx + 1:], inorder[idx + 1:])
return root
def inorderTraversal(root):
if not root:
return []
return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)
# Example
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
root = buildTree(preorder, inorder)
# Verify the constructed tree by printing its inorder traversal
print("Inorder traversal of constructed tree:", inorderTraversal(root))
go实现
package main
import "fmt"
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func buildTree(preorder []int, inorder []int) *TreeNode {
if len(preorder) == 0 || len(inorder) == 0 {
return nil
}
rootVal := preorder[0]
root := &TreeNode{Val: rootVal}
var idx int
for i, v := range inorder {
if v == rootVal {
idx = i
break
}
}
root.Left = buildTree(preorder[1:idx+1], inorder[:idx])
root.Right = buildTree(preorder[idx+1:], inorder[idx+1:])
return root
}
func inorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
left := inorderTraversal(root.Left)
right := inorderTraversal(root.Right)
return append(append(left, root.Val), right...)
}
func main() {
// Example
preorder := []int{3, 9, 20, 15, 7}
inorder := []int{9, 3, 15, 20, 7}
root := buildTree(preorder, inorder)
// Verify the constructed tree by printing its inorder traversal
fmt.Println("Inorder traversal of constructed tree:", inorderTraversal(root))
}
kotlin实现
class TreeNode(var `val`: Int) {
var left: TreeNode? = null
var right: TreeNode? = null
}
fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
if (preorder.isEmpty() || inorder.isEmpty()) {
return null
}
val rootVal = preorder[0]
val root = TreeNode(rootVal)
val idx = inorder.indexOf(rootVal)
root.left = buildTree(preorder.sliceArray(1..idx), inorder.sliceArray(0 until idx))
root.right = buildTree(preorder.sliceArray(idx + 1 until preorder.size), inorder.sliceArray(idx + 1 until inorder.size))
return root
}
fun inorderTraversal(root: TreeNode?): List<Int> {
val result = mutableListOf<Int>()
fun inorder(node: TreeNode?) {
if (node == null) return
inorder(node.left)
result.add(node.`val`)
inorder(node.right)
}
inorder(root)
return result
}
fun main() {
// Example
val preorder = intArrayOf(3, 9, 20, 15, 7)
val inorder = intArrayOf(9, 3, 15, 20, 7)
val root = buildTree(preorder, inorder)
// Verify the constructed tree by printing its inorder traversal
println("Inorder traversal of constructed tree: ${inorderTraversal(root)}")
}