zoukankan      html  css  js  c++  java
  • 100_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.

    判断两个给定的树是否相同,不追求效率,简单编码可以使用深度优先,递归的方式

    先判断两个树p和q是否为空,为空返回true,在不为空时,若p和q的左子树有一个为空或是右子树有一个为空,则一定返回false

    然后,继续递归,对p和q的左子树和右子树分别进行isSame(p, q)运算

    C语言代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    bool isSameTree(struct TreeNode* p, struct TreeNode* q) {
        if(p == NULL && q == NULL)
        {
            return 1;
        }
        else if(p == NULL || q == NULL)
        {
            return 0;
        }
        if(p->val != q->val)
        {
            return 0;
        }
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
  • 相关阅读:
    Docker
    Docker
    log4j日志类的使用
    &times被转义成x的解决方法
    java通用的jdbc数据库操作类
    java一个调用webapi的工具类
    Java 开发杂记
    J2EE名词解释
    C# 进程之间的通讯
    如何捕获全局异常
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5011924.html
Copyright © 2011-2022 走看看