BFS with Two Queue Java Solution


  • 5
    C
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        Queue<String> path = new LinkedList<>();
        path.offer(root.val + "");
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            String item = path.poll();
            if (cur.left == null && cur.right == null) {
                res.add(item);
            }
            if (cur.left != null) {
                queue.offer(cur.left);
                path.offer(item + "->" + cur.left.val + "");
            }
            if (cur.right != null) {
                queue.offer(cur.right);
                path.offer(item + "->" + cur.right.val + "");
            }
        }
        return res;
    }

Log in to reply
 

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