Java solution - backtracking


  • 0
    A
    /**
     * 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> paths = new ArrayList<>();
            List<TreeNode> buffer = new ArrayList<>();
            getPaths(root, buffer, paths);
            return paths;
        }
        
        private void getPaths(TreeNode root, List<TreeNode> buffer, List<String> results) {
            if (root == null) {
                return;
            }
            if (root.left == null && root.right == null) {
                StringBuilder sb = new StringBuilder();
                for (TreeNode n : buffer) {
                    sb.append(n.val).append("->");
                }
                sb.append(root.val);
                results.add(sb.toString());
            }
            else {
                buffer.add(root);
                getPaths(root.left, buffer, results);
                getPaths(root.right, buffer, results);
                buffer.remove(buffer.size() -1);
            }
        }
    }

Log in to reply
 

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