Skip to content

590. N-ary Tree Postorder Traversa #407

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

You must be logged in to vote

We can approach it both recursively and iteratively. Since the follow-up asks for an iterative solution, we'll focus on that. Postorder traversal means visiting the children nodes first and then the parent node.

Let's implement this solution in PHP: 590. N-ary Tree Postorder Traversal

<?php
class Node {
    public $val = null;
    public $children = [];

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

function postorder($root) {
    if ($root === null) {
        return [];
    }

    $result = [];
    $stack = [$root];
    
    while (!empty($stack)) {
        $node = array_pop($stack);
        array_unshift($result, $node->val);
        foreach ($node->children 

Replies: 1 comment 2 replies

Comment options

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

mah-shamim Aug 26, 2024
Maintainer Author

@topugit
Comment options

topugit Aug 26, 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