DEV Community

Tanuja V
Tanuja V

Posted on • Edited on

2 1

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)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more