Thursday, January 7, 2021

Find leaves of a binary tree

Problem: Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Example:


Input: Tree in the above image
Output: [[12],[11],[8,9,10],[4,5,6,7],[2,3],[1]]


Approach: We can apply Level Order traversal and get the result in level by level in a list or we can apply Pre-Order traversal and while using Pre-Order traversal we can have a parameter which will tell the current level. According to this parameter we can add current node's value in the result list.


Implementation in C#:

        public List<List<int>> FindLeaves()

        {

            if (this.Root == null)

            {

                return new List<List<int>>();

            }

            List<List<int>> result = new List<List<int>>();

            int currLevel = 1;

            this.FindLeaves(this.Root, currLevel, ref result);

            result.Reverse();

            return result;

        }


        private void FindLeaves(BinaryTreeNode node, int currLevel, ref List<List<int>> result)

        {

            if (node == null)

            {

                return;

            }

            if (result.Count < currLevel)

            {

                result.Add(new List<int>());

            }

            result[currLevel - 1].Add(node.Value);

            this.FindLeaves(node.LeftNode, currLevel + 1, ref result);

            this.FindLeaves(node.RightNode, currLevel + 1, ref result);

        }


Complexity: O(n)

No comments:

Post a Comment