leetcode - Same Tree
生活随笔
收集整理的這篇文章主要介紹了
leetcode - Same Tree
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目: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.
?
個人思路:
1、比較兩棵樹是否相同,先比較根節點是否相同,再分別比較左子樹和右子樹是否相同,可以看出這是一個遞歸的過程,一般樹的題目都會涉及遞歸
?
代碼:
1 #include <stddef.h> 2 /* 3 struct TreeNode 4 { 5 int val; 6 TreeNode *left; 7 TreeNode *right; 8 TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 }; 10 */ 11 class Solution 12 { 13 public: 14 bool isSameTree(TreeNode *p, TreeNode *q) 15 { 16 //p,q均為空 17 if (p == NULL && q == NULL) 18 { 19 return true; 20 } 21 22 //p,q不為空時,p,q指向結點的值相同且p,q左右子樹均相同,則說明p,q指向的樹相同 23 if (p != NULL && q != NULL && p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right)) 24 { 25 return true; 26 } 27 28 return false; 29 } 30 }; View Code?
按照慣例,到網上搜尋是否有更好的方法,發現大部分都是采用這種遞歸的思路,就這樣吧
轉載于:https://www.cnblogs.com/laihaiteng/p/3786077.html
總結
以上是生活随笔為你收集整理的leetcode - Same Tree的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在linux下安装配置DNS服务器
- 下一篇: 企业搜索引擎开发之连接器connecto