LeetCode100 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.(Easy)

分析:

二叉树问题往往采用递归解决比较简单,这个题就是单纯的递归问题,以此判断两个根是否为空,节点值是否相等,左右孩子是否存在且递归判定相同。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     bool isSameTree(TreeNode* p, TreeNode* q) {
13         if (p == nullptr && q == nullptr) {
14             return true;
15         }
16         else if (p == nullptr && q != nullptr) {
17             return false;
18         }
19         else if (p != nullptr && q == nullptr) {
20             return false;
21         }
22         else {
23             if (p -> val != q -> val) {
24                 return false;
25             }
26             else {
27                 return (isSameTree(p -> left, q -> left) && isSameTree(p -> right, q -> right)) ;
28             }
29         }
30     }
31 };

 

原文地址:https://www.cnblogs.com/wangxiaobao/p/6032036.html