二叉树前中后序遍历-迭代模板

122 阅读1分钟

先序和中序还是

先序

function inorderTraversal($root) {
        $res = [];
        $stack = new SplStack();
        $cur = $root;
        while (!$stack->isEmpty() || $cur) {
            while ($cur) {
                $stack->push($cur);
                $cur = $cur->left;
            }
            $tmp = $stack->pop();
            $res[] = $tmp->val;
            $cur = $tmp->right;
        }

        return $res;
    }

中序

function inorderTraversal($root) {
        $res = [];
        $stack = new SplStack();
        $cur = $root;
        while (!$stack->isEmpty() || $cur) {
            while ($cur) {
                $stack->push($cur);
                $cur = $cur->left;
            }
            $tmp = $stack->pop();
            $res[] = $tmp->val;
            $cur = $tmp->right;
        }

        return $res;
    }

主要是一个flag,flag等于1的时候才会加到结果集。 后序

function postorderTraversal($root) {
        $res = [];
        $stack = new SplStack();
        $stack->push(['flag' => 0, 'node' => $root]);
        while (!$stack->isEmpty()) {
            $t = $stack->pop();
            $flag = $t['flag'];
            $node = $t['node'];
            if (!$node) {
                continue;
            }
            if ($flag == 1) {
                $res[] = $node->val;
            } else {
                $stack->push(['flag' => 1, 'node' => $node]);
                $stack->push(['flag' => 0, 'node' => $node->right]);
                $stack->push(['flag' => 0, 'node' => $node->left]);
            }
        }
        return $res;
    }