Week3 Same Tree

100.Same Tree

问题描述

题目来自LeetCode Depth-first Search
Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Week3 Same Tree
Week3 Same Tree
Week3 Same Tree

分析

这周开始学DFS算法,找了一个简单题练习。
题目意思是给出两个二叉树,要求写一个算法来检查它们是否相同。若两棵树结构完全相同,且每个节点有相同值,则为两棵树相同。

代码

采用递归方式实现

// c++
/**
 * 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 isSameTree(TreeNode* p, TreeNode* q) {
        if(p==null && q==null)
            return true;
        else if(p==null && q != null)
        	return false;
        else if(p!=null && q == null)
        	return false;
        else if(p!=null && q != null && p->val != q->val)
        	return false;
        else
        	return(isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));
    }
};