Java iterative solution with O(1)


  • 0
    N
    /**
     * 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> inorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<Integer>();        
            if(root == null)
                return null;
            TreeNode tmpRoot = root;
            while(tmpRoot != null){
                TreeNode tmp = tmpRoot.left;
                if(tmp != null){
                    while(tmp.right != null && tmp.right != tmpRoot)
                        tmp = tmp.right;
                    if(tmp.right == null){
                        tmp.right = tmpRoot;
                        tmpRoot = tmpRoot.left;
                    }else{
                        list.add(tmpRoot.val);
                        tmpRoot = tmpRoot.right;
                    }
                }else{
                    list.add(tmpRoot.val);
                    tmpRoot = tmpRoot.right;
                }
            }
            return list;
        }
    }

  • 0
    G

    IMO if (root == null) return list; is way more elegant. Collections should be empty and not null for base/corner cases.


Log in to reply
 

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