Simple Java O(n) time and O(1) space, Morris traversal


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<Integer> preorderTraversal(TreeNode root) {
            
            /* Morris preorder traversal O(n) time & O(1) space */
            List<Integer> list = new ArrayList<>();
            TreeNode curr = root;
            while(curr!=null){
                if(curr.left == null){
                    list.add(curr.val);
                    curr = curr.right;
                }else{
                    TreeNode predecessor = curr.left;
                    while(predecessor.right!=null && predecessor.right!=curr){
                        predecessor = predecessor.right;
                    }
                    if(predecessor.right == null){
                        predecessor.right = curr;
                        list.add(curr.val);
                        curr = curr.left;
                        
                    }else{
                        predecessor.right = null;
                        
                        curr = curr.right;
                    }
                }
            }
            return list;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.