Find all leaves of a binary tree

Find all leaf nodes of binary tree.

 Example 1:

Input:        1
             / \
            2   3
               /  
              4   
Output:  2 4 

Approach:

Java

import java.util.ArrayList;
import java.util.List;

public class TreeAllleavesNode {
    public static void main(String[] args) {
        TreeNode tree = new TreeNode(1);
        tree.left = new TreeNode(2);
        tree.right = new TreeNode(3);
        tree.right.left = new TreeNode(4);
        List<IntegerallLeaves = 
new ArrayList<Integer>();
        findAllLeaves(tree, allLeaves);
        System.out.println(allLeaves);
    }

    // method to find all leaves nodes
    private static void findAllLeaves(TreeNode tree,
                 List<IntegerallLeaves) {
        // if tree is null
        if (tree == null)
            return;
        // if left and right node is null then
        // add leaves
        if (tree.left == null && 
tree.right == null) {
            allLeaves.add(tree.val);
        }
        findAllLeaves(tree.left, allLeaves);
        findAllLeaves(tree.right, allLeaves);
    }
}


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

    TreeNode() {
    }

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

    TreeNode(int valTreeNode left,
 TreeNode 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 find all
//the leaf nodes in binary tree
void allLeafNodes(TreeNode *root,vector<int&leaf)
{
    //if root is null then return
    if(root==NULL)
       return;

    //if the node is leaf node add
    //into the leaf list
    if(root->left==NULL
&&root->right==NULL)
        leaf.push_back(root->data);
    //call for left
    allLeafNodes(root->left,leaf);
    //call for right
    allLeafNodes(root->right,leaf);
}
int main()
{

    TreeNode *tree=new TreeNode(1);
    tree->left=new TreeNode(2);
    tree->right=new TreeNode(3);
    tree->right->left=new TreeNode(4);
    vector<intleaf;
    allLeafNodes(tree,leaf);
    cout<<"All leaf nodes ";
    for(int i=0;i<leaf.size();i++)
       cout<<leaf[i]<<" ";
    return 0;
}


No comments:

Post a Comment