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.
考察递归。判断两棵树相等,只要递归判断两棵树的结构和值。所以遇到一个指针为空的时候,另一个指针一定要为空。不为空的时候,两个指针的值必须相等。再递归左右子树是否相等。
/** * Definition for binary tree * 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) { bool flag = true; /* 其中一个为空,则肯定结束 */ if(p == NULL || q == NULL) { /* 两个都为空才是相等的 */ if(p == NULL && q == NULL) return true; return false; } /* 两个节点的值不等则 false */ if(p->val != q->val) return false; /* 递归判断左子树 */ flag = flag & isSameTree(p->left,q->left); /* 递归判断右子树 */ flag = flag & isSameTree(p->right,q->right); return flag; } };
原文地址:http://blog.csdn.net/jcjc918/article/details/39898499