📜  N元树的迭代后序遍历

📅  最后修改于: 2022-05-13 01:57:09.186000             🧑  作者: Mango

N元树的迭代后序遍历

给定一棵 N 叉树,任务是迭代地找到给定树的后序遍历。
例子:

Input:
     1
   / | \
  3  2  4
 / \
5   6
Output: [5, 6, 3, 2, 4, 1]

Input:
   1
  / \
 2   3
Output: [2, 3, 1]

方法:
我们已经讨论了使用一个堆栈的二叉树的迭代后序遍历。我们将把这种方法扩展到 n 叉树。这个想法很简单,对于每个节点,在遍历该节点之前,我们必须遍历该节点的所有子节点(从左到右)。
伪代码:

  • 从根开始。
  • 重复以下所有步骤,直到 root != null 或堆栈不为空。
    1. 如果 root != null 然后 push root ,它是堆栈中的一个索引,并继续向左节点。
    2. 从堆栈中弹出元素并打印它。
    3. 弹出堆栈中的所有元素,直到堆栈不为空&&弹出的节点是最后一个子节点
      这是一个父母。
    4. 将 root 分配给栈顶节点的下一个子节点。

下面是上述方法的实现:

C++
// C++ Program to iterative Postorder
// Traversal of N-ary Tree
#include
using namespace std;
 
// Node class
class Node
{
    public :
    int val;
    vector children ;
 
    // Default constructor
    Node() {}
 
    Node(int _val)
    {
        val = _val;
    }
 
    Node(int _val, vector _children)
    {
        val = _val;
        children = _children;
    }
};
     
// Helper class to push node and it's index
// into the st
class Pair
{
    public:
    Node* node;
    int childrenIndex;
    Pair(Node* _node, int _childrenIndex)
    {
        node = _node;
        childrenIndex = _childrenIndex;
    }
};
     
// We will keep the start index as 0,
// because first we always
// process the left most children
int currentRootIndex = 0;
stack st;
vector postorderTraversal ;
 
// Function to perform iterative postorder traversal
vector postorder(Node* root)
{
    while (root != NULL || st.size() > 0)
    {
        if (root != NULL)
        {
             
            // Push the root and it's index
            // into the st
            st.push(new Pair(root, currentRootIndex));
            currentRootIndex = 0;
 
            // If root don't have any children's that
            // means we are already at the left most
            // node, so we will mark root as NULL
            if (root->children.size() >= 1)
            {
                root = root->children[0];
            }
            else
            {
                root = NULL;
            }
            continue;
        }
 
        // We will pop the top of the st and
        // push_back it to our answer
        Pair* temp = st.top();
        st.pop();
        postorderTraversal.push_back(temp->node->val);
 
        // Repeatedly we will the pop all the
        // elements from the st till popped
        // element is last children of top of
        // the st
        while (st.size() > 0 && temp->childrenIndex ==
                st.top()->node->children.size() - 1)
        {
            temp = st.top();
            st.pop();
             
            postorderTraversal.push_back(temp->node->val);
        }
 
        // If st is not empty, then simply assign
        // the root to the next children of top
        // of st's node
        if (st.size() > 0)
        {
            root = st.top()->node->children[temp->childrenIndex + 1];
            currentRootIndex = temp->childrenIndex + 1;
        }
    }
    return postorderTraversal;
}
 
// Driver Code
int main()
{
    Node* root = new Node(1);
 
    root->children.push_back(new Node(3));
    root->children.push_back(new Node(2));
    root->children.push_back(new Node(4));
 
    root->children[0]->children.push_back(new Node(5));
    root->children[0]->children.push_back(new Node(6));
    vector v = postorder(root);
    for(int i = 0; i < v.size(); i++)
        cout << v[i] << " ";
}
 
// This code is contributed by Arnab Kundu


Java
// Node class
    static class Node {
        public int val;
        public List children = new ArrayList();
     
        // Default constructor
        public Node() {}
     
        public Node(int _val)
        {
            val = _val;
        }
     
        public Node(int _val, List _children)
        {
            val = _val;
            children = _children;
        }
    };
     
    // Helper class to push node and it's index
    // into the stack
    static class Pair {
        public Node node;
        public int childrenIndex;
        public Pair(Node _node, int _childrenIndex)
        {
            node = _node;
            childrenIndex = _childrenIndex;
        }
    }
     
    // We will keep the start index as 0,
    // because first we always
    // process the left most children
    int currentRootIndex = 0;
    Stack stack = new Stack();
    ArrayList postorderTraversal =
                        new ArrayList();
     
    // Function to perform iterative postorder traversal
    public ArrayList postorder(Node root)
    {
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                 
                // Push the root and it's index
                // into the stack
                stack.push(new Pair(root, currentRootIndex));
                currentRootIndex = 0;
     
                // If root don't have any children's that
                // means we are already at the left most
                // node, so we will mark root as null
                if (root.children.size() >= 1) {
                    root = root.children.get(0);
                }
                else {
                    root = null;
                }
                continue;
            }
     
            // We will pop the top of the stack and
            // add it to our answer
            Pair temp = stack.pop();
            postorderTraversal.add(temp.node.val);
     
            // Repeatedly we will the pop all the
            // elements from the stack till popped
            // element is last children of top of
            // the stack
            while (!stack.isEmpty() && temp.childrenIndex ==
                    stack.peek().node.children.size() - 1) {
                temp = stack.pop();
                 
                postorderTraversal.add(temp.node.val);
            }
     
            // If stack is not empty, then simply assign
            // the root to the next children of top
            // of stack's node
            if (!stack.isEmpty()) {
                root = stack.peek().node.children.get(
                                        temp.childrenIndex + 1);
                currentRootIndex = temp.childrenIndex + 1;
            }
        }
     
        return postorderTraversal;
    }
     
    // Driver Code
    public static void main(String[] args)
    {
        GFG solution = new GFG();
        Node root = new Node(1);
     
        root.children.add(new Node(3));
        root.children.add(new Node(2));
        root.children.add(new Node(4));
     
        root.children.get(0).children.add(new Node(5));
        root.children.get(0).children.add(new Node(6));
     
        System.out.println(solution.postorder(root));
    }
}


C#
// C# Program to iterative Postorder Traversal of N-ary Tree
using System;
using System.Collections.Generic;
 
class GFG
{
    // Node class
    public class Node
    {
        public int val;
        public List children = new List();
     
        // Default constructor
        public Node() {}
     
        public Node(int _val)
        {
            val = _val;
        }
     
        public Node(int _val, List _children)
        {
            val = _val;
            children = _children;
        }
    };
     
    // Helper class to.Push node and it's index
    // into the stack
    class Pair
    {
        public Node node;
        public int childrenIndex;
        public Pair(Node _node, int _childrenIndex)
        {
            node = _node;
            childrenIndex = _childrenIndex;
        }
    }
     
    // We will keep the start index as 0,
    // because first we always
    // process the left most children
    int currentRootIndex = 0;
    Stack stack = new Stack();
    List postorderTraversal =
                        new List();
     
    // Function to perform iterative postorder traversal
    public List postorder(Node root)
    {
        while (root != null || stack.Count != 0)
        {
            if (root != null)
            {
                 
                // Push the root and it's index
                // into the stack
                stack.Push(new Pair(root, currentRootIndex));
                currentRootIndex = 0;
     
                // If root don't have any children's that
                // means we are already at the left most
                // node, so we will mark root as null
                if (root.children.Count >= 1)
                {
                    root = root.children[0];
                }
                else
                {
                    root = null;
                }
                continue;
            }
     
            // We will.Pop the top of the stack and
            //.Add it to our answer
            Pair temp = stack.Pop();
            postorderTraversal.Add(temp.node.val);
     
            // Repeatedly we will the.Pop all the
            // elements from the stack till.Popped
            // element is last children of top of
            // the stack
            while (stack.Count != 0 && temp.childrenIndex ==
                    stack.Peek().node.children.Count - 1)
            {
                temp = stack.Pop();
                 
                postorderTraversal.Add(temp.node.val);
            }
     
            // If stack is not empty, then simply assign
            // the root to the next children of top
            // of stack's node
            if (stack.Count != 0)
            {
                root = stack.Peek().node.children[temp.childrenIndex + 1];
                currentRootIndex = temp.childrenIndex + 1;
            }
        }
     
        return postorderTraversal;
    }
     
    // Driver Code
    public static void Main(String[] args)
    {
        GFG solution = new GFG();
        Node root = new Node(1);
     
        root.children.Add(new Node(3));
        root.children.Add(new Node(2));
        root.children.Add(new Node(4));
     
        root.children[0].children.Add(new Node(5));
        root.children[0].children.Add(new Node(6));
        Console.Write("[");
        List temp = solution.postorder(root);
        int size = temp.Count;
        int count = 0;
        foreach(int v in temp)
        {
            Console.Write(v);
            count++;
            if(count < size)
                Console.Write(", ");
        }
        Console.Write("]");
    }
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
[5, 6, 3, 2, 4, 1]