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);
    }
  • 相关阅读:
    又是运行不到main的问题
    stlink问题
    AD7124踩过的坑
    stm32上调试AD5410
    linux读xml文件问题
    stm8问题记录
    430 仿真器 问题
    虚拟机VMware显示“内部错误”的解决方法
    VS2008 如何设置字体大小?
    Hyperledger Indy项目
  • 原文地址:https://www.cnblogs.com/Anthony-Wang/p/5011924.html
Copyright © 2011-2022 走看看