Welcome to Subscribe On Youtube

Formatted question description: https://leetcode.ca/all/1315.html

1315. Sum of Nodes with Even-Valued Grandparent (Medium)

Given a binary tree, return the sum of values of nodes with even-valued grandparent.  (A grandparent of a node is the parent of its parent, if it exists.)

If there are no nodes with an even-valued grandparent, return 0.

 

Example 1:

Input: root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
Output: 18
Explanation: The red nodes are the nodes with even-value grandparent while the blue nodes are the even-value grandparents.

 

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

Related Topics:
Tree, Depth-first Search

Solution 1. Pre-order Traversal

// OJ: https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
// Time: O(N)
// Space: O(N)
class Solution {
    int ans = 0;
    vector<TreeNode*> v;
    void preorder(TreeNode *root, int level) {
        if (!root) return;
        if (v.size() <= level) v.push_back(root);
        else v[level] = root;
        if (level - 2 >= 0 && v[level - 2]->val % 2 == 0) ans += root->val;
        preorder(root->left, level + 1);
        preorder(root->right, level + 1);
    }
public:
    int sumEvenGrandparent(TreeNode* root) {
        preorder(root, 0);
        return ans;
    }
};
  • /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public int sumEvenGrandparent(TreeNode root) {
            int sum = 0;
            Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
            Queue<Boolean> booleanQueue = new LinkedList<Boolean>();
            nodeQueue.offer(root);
            booleanQueue.offer(false);
            while (!nodeQueue.isEmpty()) {
                TreeNode node = nodeQueue.poll();
                boolean isEven = booleanQueue.poll();
                boolean curEven = node.val % 2 == 0;
                TreeNode left = node.left, right = node.right;
                if (left != null) {
                    if (isEven)
                        sum += left.val;
                    nodeQueue.offer(left);
                    booleanQueue.offer(curEven);
                }
                if (right != null) {
                    if (isEven)
                        sum += right.val;
                    nodeQueue.offer(right);
                    booleanQueue.offer(curEven);
                }
            }
            return sum;
        }
    }
    
    ############
    
    /**
     * Definition for a binary tree node.
     * public 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;
     *     }
     * }
     */
    class Solution {
        private int res;
    
        public int sumEvenGrandparent(TreeNode root) {
            res = 0;
            dfs(root, root.left);
            dfs(root, root.right);
            return res;
        }
    
        private void dfs(TreeNode g, TreeNode p) {
            if (p == null) {
                return;
            }
            if (g.val % 2 == 0) {
                if (p.left != null) {
                    res += p.left.val;
                }
                if (p.right != null) {
                    res += p.right.val;
                }
            }
            dfs(p, p.left);
            dfs(p, p.right);
        }
    }
    
  • // OJ: https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent/
    // Time: O(N)
    // Space: O(N)
    class Solution {
        int ans = 0;
        vector<TreeNode*> v;
        void preorder(TreeNode *root, int level) {
            if (!root) return;
            if (v.size() <= level) v.push_back(root);
            else v[level] = root;
            if (level - 2 >= 0 && v[level - 2]->val % 2 == 0) ans += root->val;
            preorder(root->left, level + 1);
            preorder(root->right, level + 1);
        }
    public:
        int sumEvenGrandparent(TreeNode* root) {
            preorder(root, 0);
            return ans;
        }
    };
    
  • # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def sumEvenGrandparent(self, root: TreeNode) -> int:
            self.res = 0
    
            def dfs(g, p):
                if p is None:
                    return
                if g.val % 2 == 0:
                    if p.left:
                        self.res += p.left.val
                    if p.right:
                        self.res += p.right.val
                dfs(p, p.left)
                dfs(p, p.right)
    
            dfs(root, root.left)
            dfs(root, root.right)
            return self.res
    
    
    
  • /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    
    var res int
    
    func sumEvenGrandparent(root *TreeNode) int {
    	res = 0
    	dfs(root, root.Left)
    	dfs(root, root.Right)
    	return res
    }
    
    func dfs(g, p *TreeNode) {
    	if p == nil {
    		return
    	}
    	if g.Val%2 == 0 {
    		if p.Left != nil {
    			res += p.Left.Val
    		}
    		if p.Right != nil {
    			res += p.Right.Val
    		}
    	}
    	dfs(p, p.Left)
    	dfs(p, p.Right)
    }
    

All Problems

All Solutions