leetcode 第三题

Same Tree

题目地址:https://leetcode.com/problems/same-tree/

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

判断两个二叉树是否相同。

利用递归即可。

ruby版:

# Definition for a binary tree node.
# class TreeNode
#     attr_accessor :val, :left, :right
#     def initialize(val)
#         @val = val
#         @left, @right = nil, nil
#     end
# end

# @param {TreeNode} p
# @param {TreeNode} q
# @return {Boolean}
def is_same_tree(p, q)
    if (q.nil? && p.nil?) 
        return true
    elsif (q.nil? || p.nil?) || (q.val != p.val)
        return false
    elsif q.val == p.val
        return is_same_tree(q.left, p.left) && is_same_tree(q.right, p.right)
    end
end