SameTree

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.
Subscribe to see which companies asked this question

题目就是判断两颗树是不是相同的树。
解决思路:依次去判断这棵树的每个节点,是否存在这个节点,每个节点的值是否一样,然后他的子节点是否相同是否遵循以上规则。这就可以用递归来做。
时间复杂度O(n),空间复杂度O(logn)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 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 == NULL&&q == NULL)
return true;
if(p == NULL||q == NULL)
return false;
if(p->val != q->val)
return false;
return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right);
}
};

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×