Skip to content

eMahtab/morris-inorder-traversal

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

6 Commits
ย 
ย 

Repository files navigation

Morris Inorder Traversal ๐Ÿ˜ฏ

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

Example:

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

Output: [1,3,2]

โ—๏ธ ๐Ÿ’ฅ Note : Implement Inorder traversal without using recursion (uses stack implicitly) or stack explicitly. ๐Ÿ˜‰

Implementation :

/**
 * 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> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if(root == null) 
            return res;
        TreeNode current = root;
        TreeNode predecessor = null;
        while(current != null){
        	if(current.left == null) {
        		res.add(current.val);
        		current = current.right;
        	} else {
        		predecessor = current.left;
        		while(predecessor.right != null && predecessor.right != current){
        			predecessor = predecessor.right;
        		}
        		if(predecessor.right == null) {
        			predecessor.right = current;
        			current = current.left;
        		} else {
        			predecessor.right = null;
        			res.add(current.val);
        			current = current.right;
        		}
        	}
        }
        return res;
    }
}

References :

  1. https://www.youtube.com/watch?v=wGXB9OWhPTg
  2. https://www.educative.io/edpresso/what-is-morris-traversal

About

Morris Inorder Traversal of a Binary Tree

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy