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,否则递归判断存在的其他情况,判断左右子树的情况。
/** * 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) { if(p==NULL&&q==NULL) return true; else if(p&&q) { if(p->val==q->val) { return isSameTree(p->left,q->left)&&isSameTree(p->right,q->right); } else { return false; } } else { return false; } } };
python:
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # @param p, a tree node # @param q, a tree node # @return a boolean def isSameTree(self, p, q): if p==None and q==None: return True elif p!=None and q==None: return False elif p==None and q!=None: return False elif p!=None and q!=None and p.val!=q.val: return False else: return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)