Same Tree [LEETCODE]
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.
======================================================================
Easy recursive solution , accepted with one submission.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSameTree(TreeNode *p, TreeNode *q) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if(NULL == p && NULL == q){ 16 return true; 17 } 18 if(NULL == p || NULL == q){ 19 return false; 20 } 21 if(p->val != q->val){ 22 return false; 23 } 24 return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 25 } 26 };

浙公网安备 33010602011771号