【Same Tree】cpp

题目:

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) {
        if ( !p && !q ) return true;
        stack<TreeNode *> sta_p,sta_q;
        if (p) sta_p.push(p);
        if (q) sta_q.push(q);
        while ( !sta_p.empty() && !sta_q.empty() ){
            TreeNode * tmp_p = sta_p.top();
            sta_p.pop();
            TreeNode * tmp_q = sta_q.top();
            sta_q.pop();
            // node val
            if ( tmp_p->val==tmp_q->val ){
                // right child
                if ( tmp_p->right && tmp_q->right ){
                    sta_p.push(tmp_p->right);
                    sta_q.push(tmp_q->right);
                }
                else if ( !tmp_p->right && !tmp_q->right )
                {}
                else{ return false; }
                // left child
                if ( tmp_p->left && tmp_q->left ){
                    sta_p.push(tmp_p->left);
                    sta_q.push(tmp_q->left);
                }
                else if ( !tmp_p->left && !tmp_q->left )
                {}
                else{ return false; }
            }
            else { return false; }
        }
        return sta_p.empty() && sta_q.empty();
    }
};

tips:

二叉树先序遍历。

1. 比较节点val

2. 比较节点right child

3. 比较节点left child

========================

学习了一个更简洁版的代码,主要简洁的地方是入栈时候不需要判断为NULL。

代码:

/**
 * 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<TreeNode *> sta_p,sta_q;
        sta_p.push(p);
        sta_q.push(q);
        while ( !sta_p.empty() && !sta_q.empty() )
        {
            p = sta_p.top();
            sta_p.pop();
            q = sta_q.top();
            sta_q.pop();
            if ( !q && !p ) continue;
            if ( !q || !p ) return false;
            if ( p->val!=q->val ) return false;
            sta_p.push(p->right);
            sta_p.push(p->left);
            sta_q.push(q->right);
            sta_q.push(q->left);
        }
        return sta_p.empty() && sta_q.empty();
    }
};
时间: 2024-11-07 17:40:00

【Same Tree】cpp的相关文章

【Symmetric Tree】cpp

题目: Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center). For example, this binary tree is symmetric: 1 / 2 2 / \ / 3 4 4 3 But the following is not: 1 / 2 2 \ 3 3 Note:Bonus points if you could solve it both

【BZOJ3669】[Noi2014]魔法森林【Link-Cut Tree】【最小生成树】

[题目链接] 一开始写了个二分a+最短路b,骗了65分,然后改成二分b+最短路a,骗了70分..发现二分是不对的之后,给答案取min,骗到了90分.出题人太不负责任了. 正解是枚举a,用LCT维护b的最小生成树. /* Telekinetic Forest Guard */ #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 500

【Recover Binary Search Tree】cpp

题目: Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? confused what "{1,#,2,3}&

【Maximum Depth of Binary Tree 】cpp

题目: Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 代码: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode

【Validate Binary Search Tree】cpp

题目: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with

【Invert Binary Tree】cpp

题目: Invert Binary Tree Total Accepted: 20346 Total Submissions: 57084My Submissions Question Solution Invert a binary tree. 4 / 2 7 / \ / 1 3 6 9 to 4 / 7 2 / \ / 9 6 3 1 Trivia:This problem was inspired by this original tweet by Max Howell: Google:

【Lowest Common Ancestor of a Binary Search Tree】cpp

题目: Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that

【Balanced Binary Tree】cpp

题目: Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1. 代码: /** * Definition for a bina

bzoj2581 [USACO 2012 Jan Gold] Cow Run【And-Or Tree】

传送门1:http://www.usaco.org/index.php?page=viewproblem2&cpid=110 传送门2:http://www.lydsy.com/JudgeOnline/problem.php?id=2581 这题我一看就知道自己不会了,只想了个O(2^n * 2 ^ n)即O(2 ^ 2n)的大暴力,也懒得打了,果断看solution. 看了之后惊呆了,看到了一种从未见过,闻所未闻的树叫做And-Or Tree,百度了一下,并没有官方中文翻译,姑且叫他"