[LeetCode] Same Tree

来源:互联网 发布:货架重量计算软件 编辑:程序博客网 时间:2024/06/09 18:20

前言

Leetcode之blabla Tree系列的一道水题。

题目

https://leetcode.com/problems/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.

分析

仍然是两种基本思路——递归与非递归,递归比较容易理解,而非递归,就是迭代。具体见代码。

代码

Recursive solution, easy to understand.

bool isSameTree(TreeNode* p, TreeNode* q) {    if (!p || !q) return q == p;// to judge p and q is both empty tree or not.    return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);}

Non-recursive solution:

class Solution {public:    bool isSameTree(TreeNode* p, TreeNode* q) {        stack<TreeNode*> stack_p;        stack<TreeNode*> stack_q;        if(p)   stack_p.push(p);//p is not empty        if(q)   stack_q.push(q);//q is not empty        while(!stack_p.empty() && !stack_q.empty()){            TreeNode* cur_p=stack_p.top();            TreeNode* cur_q=stack_q.top();            stack_p.pop();            stack_q.pop();            if(cur_p->val!=cur_q->val) return false;            if(cur_p->left) stack_p.push(cur_p->left);// cur_p->left != NULL            if(cur_q->left) stack_q.push(cur_q->left);// cur_q->left != NULL            if(stack_p.size() != stack_q.size())    return false;            if(cur_p->right) stack_p.push(cur_p->right);            if(cur_q->right) stack_q.push(cur_q->right);        }        return stack_p.size() == stack_q.size();    }};
0 0