国产探花免费观看_亚洲丰满少妇自慰呻吟_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));//左右子樹都得相同    }};


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宁远县| 宜兰市| 黄梅县| 岳池县| 四平市| 保康县| 台山市| 池州市| 永修县| 乐山市| 伽师县| 左权县| 达孜县| 临邑县| 苏尼特左旗| 水富县| 汤阴县| 南投市| 翼城县| 灵川县| 元谋县| 渝北区| 南皮县| 大余县| 金乡县| 宜君县| 隆安县| 双桥区| 治县。| 临邑县| 繁峙县| 崇州市| 保康县| 靖州| 沐川县| 九龙城区| 香港| 林周县| 水富县| 六盘水市| 台山市|