Skip to content

Latest commit

 

History

History
executable file
·
99 lines (48 loc) · 3.54 KB

100. Same Tree.md

File metadata and controls

executable file
·
99 lines (48 loc) · 3.54 KB

#

一天一道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

    }

};