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.

思路:如果兩顆二叉樹A,B的根結點都存在且他們的值相同,那麼就繼續判斷A的左子樹與B的左子樹,A的右子樹與B的右子樹是否一樣。可以採用遞歸的方法實現。

 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 && p->val == q->val)
			return isSameTree(p->left , q->left) && isSameTree(p->right , q->right);	
		else
			return false;		
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章