国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

leetcode 100.Same Tree

2019-11-08 02:57:39
字體:
來源:轉載
供稿:網友

題目鏈接:https://leetcode.com/PRoblems/same-tree/?tab=Description

題目描述:

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.

用深度優先遍歷兩個二叉樹,比較對應節點的值

方法一:

字節一開始寫的,最直接的方法

/** * 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 1;        else if((p==NULL&&q!=NULL)||(q==NULL&&p!=NULL))            return 0;        else if(p->val!=q->val)            return 0;        else if(isSameTree(p->left,q->left))            return isSameTree(p->right,q->right);        else            return 0;                }};方法二:

更簡潔的代碼

/** * 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) {            return (p==NULL&&q==NULL)||                   ((p!=NULL&&q!=NULL&&p->val==q->val)&&                   isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));//左右子樹都得相同    }};


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 玉龙| 华安县| 临沧市| 镇赉县| 从化市| 剑川县| 吉木乃县| 镇安县| 沭阳县| 达州市| 宣化县| 东光县| 日土县| 从江县| 建阳市| 漾濞| 和林格尔县| 长丰县| 综艺| 亳州市| 红河县| 沙田区| 邵阳市| 沙雅县| 城市| 达尔| 霍城县| 曲麻莱县| 汾阳市| 龙口市| 开阳县| 沂水县| 益阳市| 阳山县| 玉环县| 张家界市| 石泉县| 塔城市| 澄江县| 塔城市| 简阳市|