872. Leaf-Similar Trees
题目描述:
Consider all the leaves of a binary tree. From left to right order, the values of those leaves form a leaf value sequence.
For example, in the given tree above, the leaf value sequence is (6, 7, 4, 9, 8)
.
Two binary trees are considered leaf-similar if their leaf value sequence is the same.
Return true
if and only if the two given trees with head nodes root1
and root2
are leaf-similar.
Note:
- Both of the given trees will have between
1
and100
nodes.
解题思路:
DFS方法得到所有的叶子节点,得到叶子节点,判断就很简单了。
代码:
1 /** 2 * Definition for a binary tree node. 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 leafSimilar(TreeNode* root1, TreeNode* root2) { 13 vector<int> leafs1; 14 vector<int> leafs2; 15 getLeaf(root1, leafs1); 16 getLeaf(root2, leafs2); 17 if (leafs1.size() != leafs2.size()) 18 return false; 19 for (int i = 0; i < leafs1.size(); i++) { 20 if (leafs1[i] != leafs2[i]) 21 return false; 22 } 23 return true; 24 } 25 void getLeaf(TreeNode* root, vector<int>& leafs) { 26 if (root == NULL) 27 return; 28 getLeaf(root->left, leafs); 29 getLeaf(root->right, leafs); 30 if (root->left == NULL && root->right == NULL) { 31 leafs.push_back(root->val); 32 } 33 return; 34 } 35 };
分类:
LeetCode刷题
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core GC压缩(compact_phase)底层原理浅谈
· 现代计算机视觉入门之:什么是图片特征编码
· .NET 9 new features-C#13新的锁类型和语义
· Linux系统下SQL Server数据库镜像配置全流程详解
· 现代计算机视觉入门之:什么是视频
· 【译】我们最喜欢的2024年的 Visual Studio 新功能
· 个人数据保全计划:从印象笔记迁移到joplin
· Vue3.5常用特性整理
· 重拾 SSH:从基础到安全加固
· 为什么UNIX使用init进程启动其他进程?