首页 > 代码库 > Same Tree

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.

思路:对二叉树进行遍历即可。递归求解:

 1 class Solution { 2 public: 3     bool isSameTree( TreeNode *p, TreeNode *q ) { 4         if( !p && !q ) { return true; } 5         if( p && q && p->val == q->val ) { 6             return isSameTree( p->left, q->left ) && isSameTree( p->right, q->right ); 7         } 8         return false; 9     }10 };