日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

[LeetCode] Same Tree

發(fā)布時間:2025/5/22 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [LeetCode] Same Tree 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

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.

思路一:前序遞歸的思想。時間復雜度O(n),空間復雜度O(logN)

  

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 if (!p && !q) return true; 14 if (!p || !q ) return false; 15 16 return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right); 17 } 18 };

?

思路二:層次遍歷的思想。時間復雜度O(n), 空間復雜度O(logN)

  

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 queue<TreeNode *> s; 14 s.push(p); 15 s.push(q); 16 17 while (!s.empty()) { 18 p = s.front(); 19 s.pop(); 20 q = s.front(); 21 s.pop(); 22 if (!p && !q) continue; 23 if (!p || !q) return false; 24 if (p->val != q->val) return false; 25 26 s.push(p->left); 27 s.push(q->left); 28 s.push(p->right); 29 s.push(q->right); 30 } 31 32 return true; 33 } 34 };

?

轉載于:https://www.cnblogs.com/vincently/p/4232467.html

總結

以上是生活随笔為你收集整理的[LeetCode] Same Tree的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。