DEV Community

Tanuja V
Tanuja V

Posted on • Updated on

Sum Root to Leaf Numbers | LeetCode | Java

class Solution {
    int resSum = 0;
    public int sumNumbers(TreeNode root) {
        getSumRoot(root, 0);
        return resSum;
    }

    void getSumRoot(TreeNode node, int sum){
        if(node==null)
            return;

        sum = sum * 10 + node.val;

        if(node.left==null && node.right==null){
            resSum += sum;
            return;
        }

        getSumRoot(node.left, sum);
        getSumRoot(node.right, sum);
    }
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading :)
Feel free to comment and like the post if you found it helpful
Follow for more 🤝 && Happy Coding 🚀

If you enjoy my content, support me by following me on my other socials:
https://linktr.ee/tanujav7

Top comments (0)