判断两个二叉树是否相等

bool isSameTree(TreeNode* p, TreeNode* q) {
    if (p == nullptr && q == nullptr){
        return true;
    }
    else if (p == nullptr || q == nullptr){
        return false;
    }
    else if (p->val != q->val){
        return false;
    }
    else{
        return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
    }
}
时间: 2024-10-18 02:20:46

判断两个二叉树是否相等的相关文章

C++算法之 求二叉树中叶子节点的个数 与 判断两棵二叉树是否结构相同

//叶子节点的个数 /* (1)如果二叉树为空,返回0 (2)如果二叉树不为空且左右子树为空,返回1 (3)如果二叉树不为空,且左右子树不同时为空,返回左子树中叶子节点个数加上右子树中叶子节点个数 */ int GetLeafNodeNum(BTree* root) { if(root == NULL) return 0; if(root->m_pLeft == NULL && root->m_pRight == NULL) return 1; int LeafNumOfLef

判断两棵二叉树是否相等

算法思想:先序遍历,递归实现.先判断根节点是否相等,然后在判断左右子树是否相等.代码如下 1 //二叉树节点结构体 2 struct BinaryNode 3 { 4 int data; 5 BinaryNode * lc; 6 BinaryNode * rc; 7 }*BTree; 8 9 //判断二叉树是否相等的函数 10 11 bool isEqual(BTree T1,BTree T2) 12 { 13 if(T1 == NULL && T2 == NULL) 14 return

LeetCode刷题之三:判断两个二叉树是否相同

题目为: 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. 解题思路:这种题目也是递归操作简单 代码为: /** * Definition for binary tree * pub

LeeCode 判断两个二叉树是否相等

题目: 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. C代码: /** * Definition for a binary tree node. * struct TreeNod

二叉树基础算法--判断两棵二叉树是否相同

https://leetcode.com/problems/same-tree/ 1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution {

如何判断两颗二叉树是否相同

bool TreeTraversal(TreeNode *p, TreeNode *q){ if(!p&&!q) return true; bool result=false; if (p&&q) { if (p->val!=q->val) result = false; else result = isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); }e

Same Tree,判断两个二叉树是不是相同的树,结构相同,每个节点的值相同

算法分析:这道题很简单,利用递归即可. public class SameTree { public boolean isSameTree(TreeNode p, TreeNode q) { if(p == null) { return q == null; } if(q == null) { return p == null; } if(p.val == q.val) { return isSameTree(p.left, q.left) && isSameTree(p.right, q

LeetCode 100. Same Tree 判断两棵二叉树是否相等

Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value. Example 1: Input: 1 1 / \ / 2 3 2 3 [1,2,3], [1,2,3] Output:

比较两棵二叉树--(比较两棵二叉树是否相同/判断一棵二叉树是否是另一棵二叉树的子树)

一,问题介绍 本文章讨论两个问题: ①如何判断两棵二叉树的结构是一样的.对应的每个结点都有着相同的值.--即判断两棵二叉树是一样的 ②给定两棵二叉树,如何判断一棵二叉树是另一棵二叉树的子结构 ③给定两棵二叉树,如何判断一棵二叉树是另一棵二叉树的子树 注意,子结点与子树有那么一点点不同. 上面的二叉树B 是二叉树A 的子结构,但是不能说是二叉树A的子树.但是二叉树C 是 二叉树A的子树. 二,问题分析 1,如何判断两棵二叉树的结构是一样的.且对应的每个结点都有着相同的值. 对于①如何判断两棵二叉树