Skip to content

Latest commit

 

History

History
54 lines (40 loc) · 863 Bytes

145. Binary Tree Postorder Traversal.md

File metadata and controls

54 lines (40 loc) · 863 Bytes

145. Binary Tree Postorder Traversal

Problem Description

Given the root of a binary tree, return the postorder traversal of its nodes' values.

Example 1:

Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Analysis and Code

Recursive Solution

  • Time - O(n)
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> nodes;
        postorder(root, nodes);
        return nodes;
    }
    void postorder(TreeNode* root, vector<int>& nodes)
    {
        if(!root) return;
        postorder(root -> left, nodes);
        postorder(root -> right, nodes);
        nodes.push_back(root -> val);
    }
};

Iterative Stack Solution