leetcode--从中序与后序遍历序列构造二叉树

leeocode地址:从中序与后序遍历序列构造二叉树
给定两个整数数组 inorder 和 postorder ,其中 inorder 是二叉树的中序遍历, postorder 是同一棵树的后序遍历,请你构造并返回这颗 二叉树 。

示例 1:
在这里插入图片描述

输入:inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出:[3,9,20,null,null,15,7]
示例 2:

输入:inorder = [-1], postorder = [-1]
输出:[-1]

提示:
1 <= inorder.length <= 3000
postorder.length == inorder.length
-3000 <= inorder[i], postorder[i] <= 3000
inorder 和 postorder 都由 不同 的值组成
postorder 中每一个值都在 inorder 中
inorder 保证是树的中序遍历
postorder 保证是树的后序遍历

实现思路

中序遍历(Inorder):左子树 -> 根节点 -> 右子树
后序遍历(Postorder):左子树 -> 右子树 -> 根节点
通过给定的中序遍历和后序遍历数组,我们可以确定二叉树的根节点以及左右子树的范围。具体步骤如下:
步骤1:后序遍历的最后一个元素是根节点的值。
步骤2:在中序遍历中找到根节点的位置,其左侧为左子树的中序遍历,右侧为右子树的中序遍历。
步骤3:根据步骤2中左右子树的大小,可以在后序遍历中确定左子树和右子树的后序遍历。
递归地应用以上步骤,即可构造整棵二叉树。

代码实现

# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def buildTree(inorder, postorder):
    if not inorder or not postorder:
        return None
    
    root_val = postorder.pop()
    root = TreeNode(root_val)
    
    idx = inorder.index(root_val)
    
    root.right = buildTree(inorder[idx + 1:], postorder)
    root.left = buildTree(inorder[:idx], postorder)
    
    return root

def inorderTraversal(root):
    if not root:
        return []
    return inorderTraversal(root.left) + [root.val] + inorderTraversal(root.right)

# Example
inorder = [9, 3, 15, 20, 7]
postorder = [9, 15, 7, 20, 3]

root = buildTree(inorder, postorder)

# 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(inorder []int, postorder []int) *TreeNode {
	if len(inorder) == 0 || len(postorder) == 0 {
		return nil
	}

	rootVal := postorder[len(postorder)-1]
	root := &TreeNode{Val: rootVal}

	idx := indexOf(inorder, rootVal)

	root.Left = buildTree(inorder[:idx], postorder[:idx])
	root.Right = buildTree(inorder[idx+1:], postorder[idx:len(postorder)-1])

	return root
}

func indexOf(arr []int, val int) int {
	for i := range arr {
		if arr[i] == val {
			return i
		}
	}
	return -1
}

func inorderTraversal(root *TreeNode) []int {
	var result []int
	var inorder func(node *TreeNode)
	inorder = func(node *TreeNode) {
		if node == nil {
			return
		}
		inorder(node.Left)
		result = append(result, node.Val)
		inorder(node.Right)
	}
	inorder(root)
	return result
}

func main() {
	// Example
	inorder := []int{9, 3, 15, 20, 7}
	postorder := []int{9, 15, 7, 20, 3}

	root := buildTree(inorder, postorder)

	// 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(inorder: IntArray, postorder: IntArray): TreeNode? {
    if (inorder.isEmpty() || postorder.isEmpty()) {
        return null
    }

    val rootVal = postorder.last()
    val root = TreeNode(rootVal)

    val idx = inorder.indexOf(rootVal)

    root.left = buildTree(inorder.sliceArray(0 until idx), postorder.sliceArray(0 until idx))
    root.right = buildTree(inorder.sliceArray(idx + 1 until inorder.size), postorder.sliceArray(idx until postorder.size - 1))

    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 inorder = intArrayOf(9, 3, 15, 20, 7)
    val postorder = intArrayOf(9, 15, 7, 20, 3)

    val root = buildTree(inorder, postorder)

    // Verify the constructed tree by printing its inorder traversal
    println("Inorder traversal of constructed tree: ${inorderTraversal(root)}")
}

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 22:54:03       172 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 22:54:03       190 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 22:54:03       158 阅读
  4. Python语言-面向对象

    2024-07-10 22:54:03       171 阅读

热门阅读

  1. 奇幻的Python

    2024-07-10 22:54:03       32 阅读
  2. 记录一些简单的linux运维命令

    2024-07-10 22:54:03       30 阅读
  3. python--del

    2024-07-10 22:54:03       37 阅读
  4. BiLSTM模型实现

    2024-07-10 22:54:03       38 阅读
  5. Vue2.0和Vue3.0的区别?

    2024-07-10 22:54:03       35 阅读
  6. 网络安全应急处理流程

    2024-07-10 22:54:03       39 阅读
  7. 算法·高精度

    2024-07-10 22:54:03       37 阅读
  8. 闲聊C++与面向对象思想

    2024-07-10 22:54:03       39 阅读
  9. 路由器中 RIB 与 FIB 的区别

    2024-07-10 22:54:03       37 阅读
  10. 生成日志系统和监控

    2024-07-10 22:54:03       37 阅读
  11. Apache Spark详解

    2024-07-10 22:54:03       28 阅读
  12. qt opencv 应用举例

    2024-07-10 22:54:03       31 阅读