Sum Root to Leaf Numbers

深度遍历,用递归完成

    public int sumNumbers(TreeNode root) {
        return dfs(root,0);
    }
    
    int dfs(TreeNode root,int sum){
        if(root == null)return 0;
        sum = sum*10+root.val;
        if(root.left == null && root.right == null){
            return sum;
        }
        return dfs(root.left,sum)+dfs(root.right,sum);
    }


你可能感兴趣的:(Sum Root to Leaf Numbers)