Accepted iterative solution in Java using List


  • 0
    Z
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> valList = new ArrayList<>();
        List<TreeNode> nodeList = new ArrayList<>();
        while (root != null) {
            valList.add(root.val);
            if (root.right != null) {
                nodeList.add(root.right);
            }
            if (root.left != null) {
                root = root.left;
            } else {
                if (nodeList.size() > 0) {
                    root = nodeList.get(nodeList.size() - 1);
                    nodeList.remove(nodeList.size() - 1);
                } else {
                    break;
                }
            }
        }
        return valList;
    }

Log in to reply
 

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