起因:无聊刷力扣的二叉树,发现这段题解。

Rust

https://leetcode.com/problems/same-tree/discuss/301998/Rust-One-Line-Solution

// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// }
// 
// impl TreeNode {
//   #[inline]
//   pub fn new(val: i32) -> Self {
//     TreeNode {
//       val,
//       left: None,
//       right: None
//     }
//   }
// }
use std::rc::Rc;
use std::cell::RefCell;
impl Solution {
    pub fn is_same_tree(p: Option<Rc<RefCell<TreeNode>>>, q: Option<Rc<RefCell<TreeNode>>>) -> bool {
        p == q
    }
}

why can rust directly use == to check two tree?

Python

我大受震撼。然后想到优雅的 Py 应该也有。

查看 dataclass 发现有(本质是重载了 __eq__

from __future__ import annotations
from dataclasses import dataclass
from typing import Optional

@dataclass(eq=True)
class TreeNode:
    val: int
    left: Optional[TreeNode]
    right: Optional[TreeNode]

a1 = TreeNode(1, TreeNode(4, None, None), None)
a2 = TreeNode(1, TreeNode(4, None, None), None)
b1 = TreeNode(1, TreeNode(2, None, None), None)
assert a1 != b1
assert a1 == a2

C++

C++20 开始有比较优雅(也许)的写法。

C++ equal(==) overload, Shortcut or best way comparing all attributes

struct Foo {
    A a;
    B b;
    C c;

    // this just does memberwise == on each of the members
    // in declaration order (including base classes)
    bool operator==(Foo const&) const = default;
};

对旧版

struct Foo {
    A a;
    B b;
    C c;
    ...

private:
    auto tied() const { return std::tie(a, b, c, ...); }
bool operator==(Foo const& rhs) const { return tied() == rhs.tied(); }
};