Java BFS solution


  • 0
    L
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> res = new ArrayList<>();
            if (root == null) return res;
            Queue<TreeNode> queue = new LinkedList<>();
            Queue<String> queueStr = new LinkedList<>();
            queue.offer(root);
            queueStr.offer(String.valueOf(root.val));
            
            while (!queue.isEmpty()) {
                TreeNode node = queue.poll();
                String s = queueStr.poll();
                
                if (node.left != null) {
                    queue.offer(node.left);
                    queueStr.offer(s + "->" + node.left.val);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                    queueStr.offer(s + "->" + node.right.val);
                }
                
                // leaf node
                if (node.left == null && node.right == null) {
                    res.add(s);
                }
            }
            
            return res;
            
            
        }
    }
    

Log in to reply
 

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