从前序与中序遍历序列构造二叉树【php版】

本文介绍了一种使用迭代法构建二叉树的方法,通过前序遍历和中序遍历数组来构建二叉搜索树。该方法使用PHP实现,并通过栈结构来辅助构建过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在这里插入图片描述
迭代版

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     public $val = null;
 *     public $left = null;
 *     public $right = null;
 *     function __construct($val = 0, $left = null, $right = null) {
 *         $this->val = $val;
 *         $this->left = $left;
 *         $this->right = $right;
 *     }
 * }
 */
class Solution {

    /**
     * @param Integer[] $preorder
     * @param Integer[] $inorder
     * @return TreeNode
     */
    function buildTree($preorder, $inorder) {
        $lenPre = count($preorder);
		$lenIn = count($inorder);
		if ($lenPre == 0 || $lenIn == 0 || $lenPre != $lenIn) {
			return null;
		}
		$stack = new SplStack();
		$inorderIndex = 0;
		$root = new TreeNode($preorder[0]);
		$stack->push($root);
		for($i=1; $i<$lenPre; $i++) {
			$preVal = $preorder[$i];
			$top = $stack->top();
			if($top->val != $inorder[$inorderIndex]) {
				$node = new TreeNode($preVal);
				$top->left = $node;
				$stack->push($node);
                continue;
			}
			$curNode = null;
			while(!$stack->isEmpty() && $stack->top()->val == $inorder[$inorderIndex]) {
				$inorderIndex++;
				$curNode = $stack->pop();
			}
			$node = new TreeNode($preVal);
			$curNode->right = $node;
			$stack->push($node);
		}
		return $root;
    }
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值