Question:
How to count the number of special nodes using Python3

Summary

Let’s assume:

Methods: printKDistantfromLeaf


The method will allow us to count the number of nodes at a given distance ‘k’ from leaf nodes in a binary tree. 


Solution

#User function Template for python3

class Solution:

    #Function to return count of nodes at a given distance from leaf nodes.


    def printKDistantfromLeaf(self, root, k):

        vis=set()

        self.dfs(root,[],k,vis)

        return len(vis)

        

    def dfs(self,root,stack,k,vis):

        if root:

            stack.append(root)

            if not root.left and not root.right:

                n=len(stack)

                if n>k and (stack[-k-1] not in vis):

                    vis.add(stack[-k-1])

            self.dfs(root.left,stack,k,vis)

            self.dfs(root.right,stack,k,vis)

            stack.pop()


Explanation

  • The binary tree's root, root, and the distance from leaf nodes to count nodes, k, are the two parameters required by the printKDistantfromLeaf function.

  • A set named vis is initialized inside printKDistantfromLeaf to record visited nodes.

  • With the parameters root, stack, k, and vis, the depth-first search method, or dfs, is called. The binary tree is traversed depth-first by this function.


Suggested blogs:

>How to sort the array in ascending order using Python?

>How to keep the focus on the secondary row even after deleting that row in Python?

>How to use if/else in Python to change to a different audio channel?

>How to clone a repo into local repo and install the pip package via the local repo?

>How to fix Uncaught ReferenceError in python?

>How to Install mariaDB client efficiently inside docker?

>Steps to setup typing annotations on my script: Python

>Why nn.Dropout change the elements values of a tensor in Python?

>How to generate code with Source Generator in c# into class library project?

>How to make parabolic frame movement independent in Python?

>How to make tkinter whiteboard transparent?

>How is link class Franchise with Class Menu in Python Code?


Nisha Patel

Nisha Patel

Submit
0 Answers