100. Same Tree

xiaoxiao2021-02-28  13

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.

方法一:递归

/** * 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) { if(!p&&!q) //若两个指针均为空 return true; if(!p||!q) //若只有一个为空 return false; return p->val==q->val && isSameTree(p->left,q->left) && isSameTree(p->right,q->right); } };

方法二:

class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { stack<TreeNode*> s; s.push(p); s.push(q); while(!s.empty()) { p=s.top(); s.pop(); q=s.top(); s.pop(); if(!p && !q) continue; if(!p || !q) return false; if(p->val!=q->val) return false; s.push(p->left); s.push(q->left); s.push(p->right); s.push(q->right); } return true; //最后栈为空,正确 } };
转载请注明原文地址: https://www.6miu.com/read-2150114.html

最新回复(0)