【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.

思路:可以分别把树先序和中序遍历到两个数组,然后比较遍历序列,但空间复杂度比较大。更直接的方法是使用递归判断,即先判断根结点是否相等,然后判断左右子树是否分别相等,代码如下,时间复杂度为O(n),n为树中结点数,空间复杂度为O(k),k为树高。

/**
 * 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) 
	{
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
		// 空树相等
		if (!p && !q)
			return true;

		// 只有其中一个为空树,或者结点值不一样,则不相等
        if ((p&&!q) || (!p&&q) || p->val != q->val)
			return false;

		// 判断子树是否相等
		return isSameTree(p->left,q->left) && isSameTree(p->right,q->right);
    }
};




posted on 2013-09-18 20:33  新一  阅读(240)  评论(0编辑  收藏  举报

导航