第六周Same Tree
来源:互联网 发布:mac投影仪只显示桌面 编辑:程序博客网 时间:2024/06/14 17:00
Same Tree
Leetcode algorithms problem 100: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.问题提示
无
思路
使用递归,首先返回节点为NULL时的相等情况;两个节点都是有效指针时,如果根值不一样,返回false,一样则进入递归:根的左侧树是相同的(递归)&&根的右侧树是相同的(递归),否则返回false
代码
/** * 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 (p == q); }else { if(p->val != q->val){ return false; }else{ return (isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)); } } }};
时间复杂度: O(n)
空间复杂度: O(2^n)
阅读全文
0 0
- 第六周Same Tree
- 第六周:[Leetcode]100. Same Tree
- leetcode:100 Same Tree-每日编程第六题
- 第八周:100. Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same Tree
- Same tree
- Same Tree
- Same Tree
- Same Tree
- 面向对象三大特征-多态
- visibility: hidden 和 Visible="false"的区别
- 过滤器Filter
- java170道面试题汇总+详细解析
- 使用spring boot和thrift
- 第六周Same Tree
- Dubbo中No provider available for the service异常
- 洛谷 P1468 派对灯 Party Lamps
- php json_encode 和 json_decode
- ngnix tomcat集群 demo1
- 快速幂的学习
- Django 设置sqlite3管理员用户密码
- php var_export 和 eval
- 继承