Advertisement
jibha

Untitled

Jan 22nd, 2022
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.91 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13. public:
  14.    
  15.     int sumRootToLeaf(TreeNode* root) {
  16.        
  17.         if(root==nullptr){
  18.             return 0;
  19.         }
  20.        
  21.         if(root->left==nullptr&&root->right==nullptr){
  22.             return root->val;
  23.         }
  24.         if(root->left==nullptr){
  25.             return root->val+2*sumRootToLeaf(root->right);
  26.         }
  27.         if(root->right==nullptr){
  28.             return root->val+2*sumRootToLeaf(root->left);
  29.         }
  30.        
  31.         return root->val+2*sumRootToLeaf(root->left)+2*sumRootToLeaf(root->right);
  32.     }
  33. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement