Should be straightforward level-traverse solution but could not pass the test.


  • 0
    X

    I am confused why my following solution could not pass the OJ test. Anyone knows?

    public class Solution {
        
        private class LevelTreeNode {
            int level;
            TreeNode treeNode;
            public LevelTreeNode(TreeNode n, int level) {
                level = level;
                treeNode = n;
            }
        }
        
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            LinkedList<LevelTreeNode> queue = new LinkedList<LevelTreeNode>();
            queue.offer(new LevelTreeNode(root, 1));
            while (!queue.isEmpty()) {
                LevelTreeNode n = queue.poll();
                if (n.treeNode.left == null && n.treeNode.right == null) {
                    return n.level;
                }
                if (n.treeNode.left != null) {
                    queue.offer(new LevelTreeNode(n.treeNode.left, n.level+1));
                }
                
                if (n.treeNode.right != null) {
                    queue.offer(new LevelTreeNode(n.treeNode.right, n.level+1));
                }
            }
            return 0;
        }
    }

Log in to reply
 

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