Posts

Showing posts with the label postorder traversal

Postorder Traversal of N-ary Tree - The Coding Shala

Last Updated: 26-Jan-2021 Home >> Data Structures >> Postorder Traversal of N-ary Tree  In this post, we will learn how to Traverse the N-ary Tree in Postorder and will write a Java program for Postorder Traversal. Postorder Traversal of N-ary Tree Given an n-ary tree, return the postorder traversal of its nodes' values. For example, given a 3-ary tree:  1       /  |  \      3  2  4     / \    5   6 Return its postorder traversal as: [5,6,3,2,4,1]. Postorder Traversal of N-ary Tree Java Program Approach 1 Recursive Solution. step 1. if the root is null return list. step 2. The recursive call to all children. step 3. add root to list. step 4. return list. Java Program:  /* // Definition for a Node. class Node { public int val; public List<Node> children; public Node() {} public Node(int _val,List<Node> _children) { ...

Binary Tree Postorder Traversal - The Coding Shala

Last Updated: 19-Jan-2021 Home >> Data Structures >> Binary Tree PostOrder Traversal  In this post, we will learn how to Traverse a Binary Tree in Post-Order. Binary Tree Post-Order Traversal Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [1,null,2,3]    1     \      2     /    3 Output: [3,2,1] Post-Order Traversal of Binary Tree in Java Approach 1 Using Recursion. Java Program:   /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List < Integer > postorderTraversal ( TreeNode root ) { List < Integer > PostOrder = new ArrayList < Integer >(); if ( root == null ) return PostOrder ; PostOrder . addAll ( postorderTraversal ( root . left )); ...