迭代二叉树

Class TreeNode {
    public int $val;

    public ?TreeNode $left  = null;
    public ?TreeNode $right = null;

    public function __construct(int $x)
    {
        $this->val = $x;
    }
}

Class Solution {
    public function preorderTraversal(TreeNode $root) : ?array
    {
        if (empty($root)) return [];

        $stack  = [$root];
        $output = array();

        while (boolval($stack)) {
            $root = array_pop($stack);

            if (boolval($root)) {
                array_push($output, $root->val);
                if (boolval($root->right)) {
                    array_push($stack, $root->right);
                }
                if (boolval($root->left)) {
                    array_push($stack, $root->left);
                }
            }
        }

        return $output;
    }

     public function inorderTraversal(TreeNode $root) : ?array
    {
        $stack = $output = array();
        $curr = $root;

        while (boolval($curr) || boolval($stack)) {
            while (boolval($curr)) {
                array_push($stack, $curr);
                $curr = $curr->left;
            }
            $curr = array_pop($stack);
            array_push($output, $curr->val);
            $curr = $curr->right;
        }
        return $output;
    }

    public function postorderTraversal(TreeNode $root) : ?array
    {
        if (empty($root)) return [];

        $stack  = [$root];
        $output = array();

        while (boolval($stack)) {
            $root = array_pop($stack);

            if (boolval($root)) {
                array_push($output, $root->val);
                if (boolval($root->left)) {
                    array_push($stack, $root->left);
                }
                if (boolval($root->right)) {
                    array_push($stack, $root->right);
                }
            }
        }

        return array_reverse($output);
    }
}

$first  = new TreeNode(1);
$second = new TreeNode(2);
$third  = new TreeNode(3);

$first->right = $second;
$second->left = $third;

   //     1
   //      \
   //       2
   //      /
   //     3

$solution = new Solution();

$result['pre'] = $solution->preorderTraversal($first);
$result['in'] = $solution->inorderTraversal($first);
$result['post'] = $solution->postorderTraversal($first);


print_r($result);
Array
(
    [pre] => Array
        (
            [0] => 1
            [1] => 2
            [2] => 3
        )

    [in] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 2
        )

    [post] => Array
        (
            [0] => 3
            [1] => 2
            [2] => 1
        )

)

[Process exited 0]
本作品采用《CC 协议》,转载必须注明作者和本文链接
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!