zoukankan      html  css  js  c++  java
  • [面试真题] 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.

    广度优先遍历,考察两棵树中每一个的值以及左右孩子的值是否相等。

    Program Runtime: 8 milli secs

     1 /**
     2  * Definition for binary tree
     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         // Start typing your C/C++ solution below
    14         // DO NOT write int main() function
    15         if(q == p){
    16             return true;
    17         }
    18         queue<TreeNode*> qq, qp;
    19         if(NULL == p && NULL == q){
    20             return true;
    21         }else if(NULL != p && NULL != q){
    22             qq.push(q);
    23             qp.push(p);
    24         }else{
    25             return false;
    26         }
    27         while(qq.size() != 0 && qp.size() != 0){
    28             TreeNode *curp = qp.front();
    29             qp.pop();
    30             TreeNode *curq = qq.front();
    31             qq.pop();
    32             if(curq->val != curp->val){
    33                 return false;
    34             }
    35             if(curp->left && curq->left) {
    36                 if(curp->left->val != curq->left->val){
    37                     return false;
    38                 }
    39                 qp.push(curp->left);
    40                 qq.push(curq->left);
    41             }else if(curp->left != NULL && curq->left == NULL){
    42                 return false;
    43             }else if(curp->left == NULL && curq->left != NULL){
    44                 return false;
    45             }
    46             if(curp->right && curq->right) {
    47                 if(curp->right->val != curq->right->val){
    48                     return false;
    49                 }
    50                 qp.push(curp->right);
    51                 qq.push(curq->right);
    52             }else if(curp->right != NULL && curq->right == NULL){
    53                 return false;
    54             }else if(curp->right == NULL && curq->right != NULL){
    55                 return false;
    56             }
    57         }
    58         if(qq.size() != 0 || qp.size() != 0){
    59             return false;
    60         }
    61         return true;
    62     }
    63 };
  • 相关阅读:
    windows安装nacos
    anki处理
    minikube安装net5
    在.net core中使用属性注入
    C# 使用MD5算法对密码进行加密
    c# 获取本机系统已经安装的打印机信息
    C# 比较两个datatable并找出修改差异的值
    打印机点击打印后无反应
    GUID转换成16位字符串或19位数据(确保唯一)
    RESTful
  • 原文地址:https://www.cnblogs.com/infinityu/p/3073493.html
Copyright © 2011-2022 走看看