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<Integer> allLeaves =new ArrayList<Integer>();findAllLeaves(tree, allLeaves);System.out.println(allLeaves);}// method to find all leaves nodesprivate static void findAllLeaves(TreeNode tree,List<Integer> allLeaves) {// if tree is nullif (tree == null)return;// if left and right node is null then// add leavesif (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 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 find all//the leaf nodes in binary treevoid allLeafNodes(TreeNode *root,vector<int> &leaf){//if root is null then returnif(root==NULL)return;//if the node is leaf node add//into the leaf listif(root->left==NULL&&root->right==NULL)leaf.push_back(root->data);//call for leftallLeafNodes(root->left,leaf);//call for rightallLeafNodes(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<int> leaf;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