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.
解题思路:先推断当前根节点是否同样。
假设都为空,则直接返回true。假设当前根节不为空且存储的值同样,则递归地推断左子树和右子树是否同样。
其它情况返回false。
代码:
bool isSameTree(TreeNode *p,TreeNode *q) { if(p == NULL && q == NULL) return true; if(p == NULL && q != NULL) return false; if(p != NULL && q == NULL) return false; if(p->val != q->val) return false; else { bool isLeftSubtreeSame; bool isRightSubtreeSame; isLeftSubtreeSame = isSameTree(p->left,q->left); isRightSubtreeSame = isSameTree(p->right,q->right); if(isLeftSubtreeSame && isRightSubtreeSame) return true; else return false; } }