Welcome to Subscribe On Youtube

145. Binary Tree Postorder Traversal

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]

 

Constraints:

  • The number of the nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

 

Follow up: Recursive solution is trivial, could you do it iteratively?

Solutions

1. Recusive Traversal

2. Non-recursive using Stack

3. Morris Traversal

  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
    class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            LinkedList<Integer> ans = new LinkedList<>();
            while (root != null) {
                if (root.right == null) {
                    ans.addFirst(root.val);
                    root = root.left;
                } else {
                    TreeNode next = root.right;
                    while (next.left != null && next.left != root) {
                        next = next.left;
                    }
                    if (next.left == null) {
                        ans.addFirst(root.val);
                        next.left = root;
                        root = root.right;
                    } else {
                        next.left = null;
                        root = root.left;
                    }
                }
            }
            return ans;
        }
    }
    
  • /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
     *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
     *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
     * };
     */
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            vector<int> ans;
            while (root) {
                if (!root->right) {
                    ans.push_back(root->val);
                    root = root->left;
                } else {
                    TreeNode* next = root->right;
                    while (next->left && next->left != root) {
                        next = next->left;
                    }
                    if (!next->left) {
                        ans.push_back(root->val);
                        next->left = root;
                        root = root->right;
                    } else {
                        next->left = nullptr;
                        root = root->left;
                    }
                }
            }
            reverse(ans.begin(), ans.end());
            return ans;
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def postorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
            ans = []
            while root:
                if root.right is None:
                    ans.append(root.val)
                    root = root.left
                else:
                    next = root.right
                    while next.left and next.left != root:
                        next = next.left
                    if next.left != root:
                        ans.append(root.val)
                        next.left = root
                        root = root.right
                    else:
                        next.left = None
                        root = root.left
            return ans[::-1]
    
    
  • /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    func postorderTraversal(root *TreeNode) []int {
    	var ans []int
    	for root != nil {
    		if root.Right == nil {
    			ans = append([]int{root.Val}, ans...)
    			root = root.Left
    		} else {
    			next := root.Right
    			for next.Left != nil && next.Left != root {
    				next = next.Left
    			}
    			if next.Left == nil {
    				ans = append([]int{root.Val}, ans...)
    				next.Left = root
    				root = root.Right
    			} else {
    				next.Left = nil
    				root = root.Left
    			}
    		}
    	}
    	return ans
    }
    
  • /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     val: number
     *     left: TreeNode | null
     *     right: TreeNode | null
     *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.left = (left===undefined ? null : left)
     *         this.right = (right===undefined ? null : right)
     *     }
     * }
     */
    
    function postorderTraversal(root: TreeNode | null): number[] {
        if (root == null) return [];
        let stack = [];
        let ans = [];
        let prev = null;
        while (root || stack.length) {
            while (root) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if (!root.right || root.right == prev) {
                ans.push(root.val);
                prev = root;
                root = null;
            } else {
                stack.push(root);
                root = root.right;
            }
        }
        return ans;
    }
    
    
  • // Definition for a binary tree node.
    // #[derive(Debug, PartialEq, Eq)]
    // pub struct TreeNode {
    //   pub val: i32,
    //   pub left: Option<Rc<RefCell<TreeNode>>>,
    //   pub right: Option<Rc<RefCell<TreeNode>>>,
    // }
    //
    // impl TreeNode {
    //   #[inline]
    //   pub fn new(val: i32) -> Self {
    //     TreeNode {
    //       val,
    //       left: None,
    //       right: None
    //     }
    //   }
    // }
    use std::rc::Rc;
    use std::cell::RefCell;
    impl Solution {
        fn dfs(root: &Option<Rc<RefCell<TreeNode>>>, res: &mut Vec<i32>) {
            if root.is_none() {
                return;
            }
            let node = root.as_ref().unwrap().borrow();
            Self::dfs(&node.left, res);
            Self::dfs(&node.right, res);
            res.push(node.val);
        }
    
        pub fn postorder_traversal(root: Option<Rc<RefCell<TreeNode>>>) -> Vec<i32> {
            let mut res = vec![];
            Self::dfs(&root, &mut res);
            res
        }
    }
    
    

All Problems

All Solutions