Sunday, September 6, 2020

Leetcode discuss: 1315. Sum of Nodes with Even-Valued Grandparent

 Here is the link. 

C# Apply level order traversal and also enqueue a node and it's parent and grandparent

August 31, 2020
1315. Sum of Nodes with Even-Valued Grandparent

The algorithm can easily be solved by using level order traversal and also enqueuing node and it's parent and grandparent node.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    /// <summary>
        /// August 31, 2020
        /// apply level order traversal, and also pass parent and grandparent nodes in the queue
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public int SumEvenGrandparent(TreeNode root)
        {
            if (root == null)
            {
                return 0; 
            }

            var queue = new Queue<TreeNode[]>();

            queue.Enqueue(new TreeNode[]{root, null, null});
            var sum = 0; 

            while (queue.Count > 0)
            {
                var levelSize = queue.Count;

                for (int i = 0; i < levelSize; i++)
                {
                    var node = queue.Dequeue();
                    var grandParent = node[2];
                    var isEven = grandParent != null && grandParent.val %2 == 0;

                    if (isEven)
                    {
                        sum += node[0].val;
                    }

                    var current = node[0];
                    if (current.left != null)
                    {
                        queue.Enqueue(new TreeNode[]{current.left, current, node[1]});
                    }

                    if (current.right != null)
                    {
                        queue.Enqueue(new TreeNode[] { current.right, current, node[1] });
                    }
                }
            }

            return sum; 
        }
}


No comments:

Post a Comment