【一天一道LeetCode】#100. Same Tree(100题大关)

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github
欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处

(一)题目

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 a binary tree node.
 * 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) {
        stack<pair<TreeNode*,TreeNode*>> TwoTreeNode;//用栈实现非递归
        TwoTreeNode.push(make_pair<TreeNode*,TreeNode*>((TreeNode*)p,(TreeNode*)q));//初始化
        while(!TwoTreeNode.empty())
        {
            auto temp = TwoTreeNode.top();//去除栈顶
            TwoTreeNode.pop();//处理当前节点
            TreeNode* ptemp = temp.first;
            TreeNode* qtemp = temp.second;
            if(ptemp==NULL&&qtemp==NULL) continue;//两个都为空
            else if(ptemp!=NULL&&qtemp!=NULL){//两个都不为空
                if(ptemp->val==qtemp->val)//判断值是否相等
                {
                    TwoTreeNode.push(make_pair(ptemp->left,qtemp->left));//相等则放入栈等待处理
                    TwoTreeNode.push(make_pair(ptemp->right,qtemp->right));
                }
                else return false;//不相等返回false
            }
            else return false;//一个为空另一个不为空直接返回false
        }
        return true;//全部处理完都相等就返回true
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值