Sum of Left Leaves

Find the sum of all left leaves in a given binary tree.

Example:

    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

Approach

Java

public class TreeLeftSum {
    public static void main(String[] args) {
        TreeNode tree = new TreeNode(3);
        tree.left = new TreeNode(9);
        tree.right = new TreeNode(20);
        tree.right.left = new TreeNode(15);
        tree.right.right = new TreeNode(7);
        int sum = treeLeftSum(tree);
        System.out.println(sum);
    }

    public static int treeLeftSum(TreeNode root) {
        int sum = 0;
        if (root != null) {
            // check node is leaf node
            if (isleaf(root.left))
                sum += root.left.val;
            // call for both site
            sum += treeLeftSum(root.left) + treeLeftSum(root.right);
        }
        return sum;

    }

    // function to check for
    // leaf node
    static boolean isleaf(TreeNode root) {
        // if tree is empty
        if (root == null)
            return false;

        // if the node is leaf node
        if (root.left == null && root.right == null)
            return true;
        return false;
    }
}


class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

//struct for treenode
struct TreeNode{
    int data;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int data)
    {
        this->data=data;
        this->left=NULL;
        this->right=NULL;
    }
};


//function to check for
//leaf node
bool isleaf(TreeNode *root)
{
   //if tree is empty
    if(root==NULL)
        return false;
    
    //if the  node is leaf node
    if(root->left==NULL &&root->right== NULL)
        return true;
   return false;
}

//function to find the sum of left
//leaf nodes
int sumOfLeftLeaves(TreeNode* root
{
   int res=0;
    if(root!=NULL)
        {

         //left leaf node
          if(isleaf(root->left))
                  res+=root->left->data;
           else
               res+=sumOfLeftLeaves(root->left);
            res+=sumOfLeftLeaves(root->right);
     }
        return res;
}
int main()
{
  TreeNode *root=new TreeNode(3);
  root->left=new TreeNode(9);
  root->right=new TreeNode(20);
  root->right->left=new TreeNode(15);
  root->right->right=new TreeNode(7);
  int sum=sumOfLeftLeaves(root);
  cout<<sum<<"\n";
  return 0;
}


No comments:

Post a Comment