LeetCode 2236. Determine whether the root node is equal to the sum of child nodes

【LetMeFly】2236. Determine whether the root node is equal to the sum of child nodes

Leetcode question link: https://leetcode.cn/problems/root-equals-sum-of-children/

You are given the root node of  a binary treeroot . The binary tree  3 consists of exactly three nodes: the root node, the left child node, and the right child node.

If the root node value is equal to the sum of the two child node values, return it  true , otherwise return it . false

 

Example 1:

Input: root = [10,4,6]
 Output: true
 Explanation: The values ​​of the root node, left subnode and right subnode are 10, 4 and 6 respectively. 
Since 10 is equal to 4 + 6, it returns true.

Example 2:

Input: root = [5,3,1]
 Output: false
 Explanation: The values ​​of the root node, left subnode and right subnode are 5, 3 and 1 respectively. 
Since 5 is not equal to 3 + 1, false is returned.

 

hint:

  • The tree only contains the root node, left child node and right child node
  • -100 <= Node.val <= 100

Method 1: Simulation

Determine root.val root.valroo t . v a l is equal to $root.left.val + root.right.val.

  • Time complexity O ( 1 ) O(1)O(1)
  • Space complexity O ( 1 ) O(1)O(1)

AC code

C++

class Solution {
    
    
public:
    bool checkTree(TreeNode* root) {
    
    
        return root->val == root->left->val + root->right->val;
    }
};

Python

# 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 checkTree(self, root: TreeNode) -> bool:
        return root.val == root.left.val + root.right.val

The article is published simultaneously on CSDN. It is not easy to be original. Please attach the link to the original article after reprinting with the author's consent ~
Tisfy: https://letmefly.blog.csdn.net/article/details/132388754

Guess you like

Origin blog.csdn.net/Tisfy/article/details/132388754