返回介绍

solution / 1300-1399 / 1315.Sum of Nodes with Even-Valued Grandparent / README_EN

发布于 2024-06-17 01:03:20 字数 6467 浏览 0 评论 0 收藏 0

1315. Sum of Nodes with Even-Valued Grandparent

中文文档

Description

Given the root of a binary tree, return _the sum of values of nodes with an even-valued grandparent_. If there are no nodes with an even-valued grandparent, return 0.

A grandparent of a node is the parent of its parent if it exists.

 

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.

Example 2:

Input: root = [1]
Output: 0

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 1 <= Node.val <= 100

Solutions

Solution 1: DFS

We design a function $dfs(root, x)$, which represents the sum of the values of the nodes that meet the conditions in the subtree with $root$ as the root node and $x$ as the value of the parent node of $root$. The answer is $dfs(root, 1)$.

The execution process of the function $dfs(root, x)$ is as follows:

  • If $root$ is null, return $0$.
  • Otherwise, we recursively calculate the answers of the left and right subtrees of $root$, that is, $dfs(root.left, root.val)$ and $dfs(root.right, root.val)$, and add them to the answer. If $x$ is even, we check whether the left and right children of $root$ exist. If they exist, we add their values to the answer.
  • Finally, return the answer.

The time complexity is $O(n)$, and the space complexity is $O(n)$. Where $n$ is the number of nodes.

# 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:
    def dfs(root: TreeNode, x: int) -> int:
      if root is None:
        return 0
      ans = dfs(root.left, root.val) + dfs(root.right, root.val)
      if x % 2 == 0:
        if root.left:
          ans += root.left.val
        if root.right:
          ans += root.right.val
      return ans

    return dfs(root, 1)
/**
 * 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 {
  public int sumEvenGrandparent(TreeNode root) {
    return dfs(root, 1);
  }

  private int dfs(TreeNode root, int x) {
    if (root == null) {
      return 0;
    }
    int ans = dfs(root.left, root.val) + dfs(root.right, root.val);
    if (x % 2 == 0) {
      if (root.left != null) {
        ans += root.left.val;
      }
      if (root.right != null) {
        ans += root.right.val;
      }
    }
    return ans;
  }
}
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *   int val;
 *   TreeNode *left;
 *   TreeNode *right;
 *   TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *   TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *   TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
  int sumEvenGrandparent(TreeNode* root) {
    function<int(TreeNode*, int)> dfs = [&](TreeNode* root, int x) {
      if (!root) {
        return 0;
      }
      int ans = dfs(root->left, root->val) + dfs(root->right, root->val);
      if (x % 2 == 0) {
        if (root->left) {
          ans += root->left->val;
        }
        if (root->right) {
          ans += root->right->val;
        }
      }
      return ans;
    };
    return dfs(root, 1);
  }
};
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *   Val int
 *   Left *TreeNode
 *   Right *TreeNode
 * }
 */
func sumEvenGrandparent(root *TreeNode) int {
  var dfs func(*TreeNode, int) int
  dfs = func(root *TreeNode, x int) int {
    if root == nil {
      return 0
    }
    ans := dfs(root.Left, root.Val) + dfs(root.Right, root.Val)
    if x%2 == 0 {
      if root.Left != nil {
        ans += root.Left.Val
      }
      if root.Right != nil {
        ans += root.Right.Val
      }
    }
    return ans
  }
  return dfs(root, 1)
}
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *   val: number
 *   left: TreeNode | null
 *   right: TreeNode | null
 *   constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 *   }
 * }
 */

function sumEvenGrandparent(root: TreeNode | null): number {
  const dfs = (root: TreeNode | null, x: number): number => {
    if (!root) {
      return 0;
    }
    const { val, left, right } = root;
    let ans = dfs(left, val) + dfs(right, val);
    if (x % 2 === 0) {
      ans += left?.val ?? 0;
      ans += right?.val ?? 0;
    }
    return ans;
  };
  return dfs(root, 1);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文