zoukankan      html  css  js  c++  java
  • LeetCode——same-tree

    Question

    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.

    Solution

    递归判断,首先要判断结构是否一样,如果不一样直接返回false,如果结构一样,那么要继续判断值是否相等,如果不等直接返回false,如果相等,那么继续遍历左子树和右子树。

    Code

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isSameTree(TreeNode *p, TreeNode *q) {
            if (p == NULL && q == NULL)
                return true;
            if (p == NULL)
                return false;
            if (q == NULL)
                return false;
            if (p->val == q->val) {
                 return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
            } else
                return false;
        }
    };
    
  • 相关阅读:
    java类加载机制
    java反射
    java注解
    设计模式 单例模式
    #1015 : KMP算法
    idea 快捷键
    基础数据类型综合
    工厂模式 VS 策略模式
    AtomicI 多线程中的原子操作
    ThreadLocal<T>
  • 原文地址:https://www.cnblogs.com/zhonghuasong/p/7081237.html
Copyright © 2011-2022 走看看