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 nodeif (isleaf(root.left))sum += root.left.val;// call for both sitesum += treeLeftSum(root.left) + treeLeftSum(root.right);}return sum;}// function to check for// leaf nodestatic boolean isleaf(TreeNode root) {// if tree is emptyif (root == null)return false;// if the node is leaf nodeif (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 val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};//function to check for//leaf nodebool isleaf(TreeNode *root){//if tree is emptyif(root==NULL)return false;//if the node is leaf nodeif(root->left==NULL &&root->right== NULL)return true;return false;}//function to find the sum of left//leaf nodesint sumOfLeftLeaves(TreeNode* root){int res=0;if(root!=NULL){//left leaf nodeif(isleaf(root->left))res+=root->left->data;elseres+=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