LeetCode:Same Tree

Posted walker lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Same Tree相关的知识,希望对你有一定的参考价值。

Same Tree




Total Accepted: 132356 Total Submissions: 304237 Difficulty: Easy

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.

Subscribe to see which companies asked this question

Hide Tags
 Tree Depth-first Search













c++ code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
bool isSam;
/*
void preOrder(TreeNode* p, TreeNode* q)
{
    if(!isSam) return;
    if(NULL == p && NULL == q) return;
    if(NULL == p && NULL!= q || NULL != p && NULL== q) 
    {
        isSam = false;
        return;
    }
    if(p->val != q->val)
    {
        isSam = false;
        return;
    }
    preOrder(p->left, q->left);
    preOrder(p->right, q->right);
}
*/
void inOrder(TreeNode* p, TreeNode* q)
{
    if(!isSam) return;
    if(NULL == p && NULL == q) return;
    if(NULL == p && NULL!= q || NULL != p && NULL== q) 
    {
        isSam = false;
        return;
    }
    inOrder(p->left, q->left);
    if(p->val != q->val)
    {
        isSam = false;
        return;
    }
    inOrder(p->right, q->right);
}


class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        isSam = true;
        //preOrder(p,q);
        inOrder(p,q);
        return isSam;
    }
};


以上是关于LeetCode:Same Tree的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Same Tree

Leetcode--Same Tree(0100)

★leetcode★ same-tree

Python3解leetcode Same TreeBinary Tree Level Order Traversal II

添加片段时的 FlyOut 菜单设计问题

js+数据库生成三级动态tree导航菜单