Inorder Traversal Java solution both iteration and recursion


  • 0
    K
    // recursive
    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            if (root == null) return result;
            inordtree(result, root);
            return result;
        }
        private void inordtree(List<Integer> result, TreeNode node){
            if (node.left != null) inordtree(result, node.left);
            result.add(node.val);
            if (node.right != null) inordtree(result,node.right);
        }
    }
    
    // iterative
    public class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            //stack.push(root);
            while(!stack.isEmpty() || root != null){
                if (root != null){
                    stack.push(root);
                    root = root.left;
                }
                else{
                    root = stack.pop();
                    result.add(root.val);
                    root = root.right;
                }
            }
            return result;
        }
    }

Log in to reply
 

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