Java solution, both recursion and iteration


  • 4
    H
    public List<Integer> preorderTraversal(TreeNode root) {
        // root --> left --> right
        // recursion method
        List<Integer> res = new ArrayList<>();
        if (root == null) return res;
        res.add(root.val);
        if (root.left != null) 
            for (int left : preorderTraversal(root.left)) res.add(left);
        if (root.right != null) 
            for (int right : preorderTraversal(root.right)) res.add(right);
        return res;
    }
    

    public List<Integer> preorderTraversal(TreeNode root) {
        // root --> left --> right
        // iteration method
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) return res;
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode temp = stack.pop();
            if (temp != null) {
                res.add(temp.val);
                stack.push(temp.right);
                stack.push(temp.left);
            }
        }
        return res;
    }

Log in to reply
 

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