leetcode 100 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.

Subscribe to see which companies asked this question


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool same(TreeNode *p, TreeNode *q) {
		if(p==NULL && q==NULL) return true;
		if(p==NULL || q==NULL) return false;
		if(p->val!=q->val) return false;
		if(!same(p->left, q->left)) return false;
		return same(p->right, q->right);
	}
	bool isSameTree(TreeNode *p, TreeNode *q) {
		return same(p, q);
	}
};




阅读更多
个人分类: Leetcode
上一篇leetcode 098 Validate Binary Search Tree
下一篇leetcode 101 Symmetric Tree
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭