Clean Java solution using DFS


  • 1
    W
    public class Solution {
        List<String> result = new ArrayList<String>();
        public List<String> binaryTreePaths(TreeNode root) {
            dfs(root, "");
            return result;
        }
        
        void dfs(TreeNode node, String path) {
            if(node == null)
                return;
            path = path + node.val;
            if(isLeafNode(node))
                result.add(path);
            path = path + "->";
            dfs(node.left, path);
            dfs(node.right, path);
        }
        
        boolean isLeafNode(TreeNode node) {
            return node.left == null && node.right == null;
        }
    }

  • 0
    Z

    Nice algorithm.
    One irrelevant question,this variable "path",how and when does the system allocate space to it?


Log in to reply
 

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