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
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的主要内容,如果未能解决你的问题,请参考以下文章
Python3解leetcode Same TreeBinary Tree Level Order Traversal II