Java Solution DFS


  • 3
    P
    public class Solution {
        public List<String> binaryTreePaths(TreeNode root) {
            List<String> rootLeafPath = new ArrayList<String>();
            if (root == null) return rootLeafPath;
            
            List<TreeNode> path = new LinkedList<TreeNode>();
            DFS(root, path , rootLeafPath);
            return rootLeafPath;
        }
        
        private void DFS(TreeNode root, List<TreeNode> path,   List<String> rootLeafPath){
            path.add(root);
            if (root.left != null) DFS(root.left, path, rootLeafPath);
            if (root.right != null) DFS(root.right, path, rootLeafPath);
            if (root.left == null && root.right == null) {
                StringBuilder sb = new StringBuilder();
                // print all value in current path
                for (int i = 0; i < path.size(); i++){
                    sb.append(path.get(i).val);
                    if (i != path.size()-1) sb.append("->");
                }
                rootLeafPath.add(sb.toString());
            }
            path.remove(path.size()-1);
        }
    }

Log in to reply
 

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