zoukankan      html  css  js  c++  java
  • 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 };

     

  • 相关阅读:
    浅谈最长上升子序列(LIS)
    浅谈树链剖分
    数字计数
    windy数
    骑士(树形dp)
    旅游规划
    皇宫看守
    k8s安装报错
    linux文件夹存储潜规则
    搭建覆盖率测试环境
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/6032036.html
Copyright © 2011-2022 走看看