Skip to content

145. Binary Tree Postorder Traversal #400

Answered by topugit
mah-shamim asked this question in Q&A
Discussion options

You must be logged in to vote

We can use an iterative approach with a stack. Postorder traversal follows the order: Left, Right, Root.

Let's implement this solution in PHP: 145. Binary Tree Postorder Traversal

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

function postorderTraversal($root) {
    $result = [];
    if ($root === null) {
        return $result;
    }
    
    $stack = [];
    $lastVisitedNode = null;
    $current = $root;
    
    while (!empty($stack)…

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@mah-shamim
Comment options

mah-shamim Aug 25, 2024
Maintainer Author

@topugit
Comment options

topugit Aug 25, 2024
Collaborator

Answer selected by mah-shamim
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants