965. Univalued Binary Tree

LeetCode easy original: C# #csharp #easy #graph #leetcode #tree #two-pointers
O texto da tarefa é traduzido do russo para o idioma selecionado. O código permanece sem alterações.

Бинарное árvore является одноценным, если каждый узел в дереве имеет одинаковое значение.

Дан корень бинарного дерева, return true, если данное árvore является одноценным, или false в противном случае.

Exemplo:

Input: root = [1,1,1,1,1,null,1]

Output: true

C# solução

correspondente/original
public class Solution {
    private List<int> vals;
    public bool IsUnivalTree(TreeNode root) {
        vals = new List<int>();
        Dfs(root);
        foreach (int v in vals) {
            if (v != vals[0]) {
                return false;
            }
        }
        return true;
    }
    private void Dfs(TreeNode node) {
        if (node != null) {
            vals.Add(node.val);
            Dfs(node.left);
            Dfs(node.right);
        }
    }
}

C++ solução

rascunho automático, revisar antes de enviar
#include <bits/stdc++.h>
using namespace std;

// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
    private List<int> vals;
    public bool IsUnivalTree(TreeNode root) {
        vals = new List<int>();
        Dfs(root);
        foreach (int v in vals) {
            if (v != vals[0]) {
                return false;
            }
        }
        return true;
    }
    private void Dfs(TreeNode node) {
        if (node != null) {
            vals.push_back(node.val);
            Dfs(node.left);
            Dfs(node.right);
        }
    }
}

Java solução

rascunho automático, revisar antes de enviar
import java.util.*;
import java.math.*;

// Auto-generated Java draft from the C# solution. Review API differences before LeetCode submit.
public class Solution {
    private List<int> vals;
    public boolean IsUnivalTree(TreeNode root) {
        vals = new List<int>();
        Dfs(root);
        foreach (int v in vals) {
            if (v != vals[0]) {
                return false;
            }
        }
        return true;
    }
    private void Dfs(TreeNode node) {
        if (node != null) {
            vals.add(node.val);
            Dfs(node.left);
            Dfs(node.right);
        }
    }
}

Python solução

correspondente/original
class Solution:
    def isUnivalTree(self, root: TreeNode) -> bool:
        vals = []
        
        def dfs(node):
            if node:
                vals.append(node.val)
                dfs(node.left)
                dfs(node.right)
        
        dfs(root)
        return all(v == vals[0] for v in vals)

Go solução

correspondente/original
func isUnivalTree(root *TreeNode) bool {
    vals := []int{}
    
    var dfs func(node *TreeNode)
    dfs = func(node *TreeNode) {
        if node != nil {
            vals = append(vals, node.Val)
            dfs(node.Left)
            dfs(node.Right)
        }
    }
    
    dfs(root)
    for _, v := range vals {
        if v != vals[0] {
            return false
        }
    }
    return true
}

Algorithm

Выполните обход дерева в глубину (DFS), чтобы собрать все значения узлов в список.

Проверьте, что все значения в списке одинаковы.

Если все значения одинаковы, return true, иначе return false.

😎

Vacancies for this task

vagas ativas with overlapping task tags are mostradas.

Todas as vagas
Ainda não há vagas ativas.