判断一棵树里是否有两个节点的值之和等于某个值。

653. Two Sum IV - Input is a BST

Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input: 5/ \3   6/ \   \
2   4   7Target = 9Output: True

Example 2:

Input: 5/ \3   6/ \   \
2   4   7Target = 28Output: False思路:使用 unordered_set存储?节点的值。
/*** 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 {
private:unordered_set<int> s;bool dfs(TreeNode* root,int k, unordered_set<int>& s){if(root==nullptr) return false;if(s.count(k-root->val)) return true;s.insert(root->val);return dfs(root->left,k,s)||dfs(root->right,k,s);}
public:bool findTarget(TreeNode* root, int k) {s.clear();return dfs(root,k,s);}
};

python代码

创建集合 set(), 插入 add (c++ insert)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def helper(self,root,k,s):if not root:return Falseif k-root.val in s:return Trues.add(root.val)return self.helper(root.left,k,s) or self.helper(root.right,k,s)def findTarget(self, root, k):""":type root: TreeNode:type k: int:rtype: bool"""s=set()return self.helper(root,k,s)

606. Construct String from Binary Tree

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

Example 1:

Input: Binary tree: [1,2,3,4]1/   \2     3/    4     Output: "1(2(4))(3)"
Explanation: Originallay it needs to be "1(2(4)())(3()())", but you need to omit all the unnecessary empty parenthesis pairs. And it will be "1(2(4))(3)".

Example 2:

Input: Binary tree: [1,2,3,null,4]1/   \2     3\  4 Output: "1(2()(4))(3)"
Explanation: Almost the same as the first example, except we can't omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
/*** 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:string tree2str(TreeNode* t) {if(t==nullptr)return "";string s=to_string(t->val);if(t->left==nullptr){if(t->right==nullptr)return s;else{return s+"()"+"("+tree2str(t->right)+")";}}else{return s+"("+tree2str(t->left)+")"+(!t->right?"":"("+tree2str(t->right)+")");}}
};

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def tree2str(self, t):""":type t: TreeNode:rtype: str"""if not t:return ""if not t.left:return str(t.val)+("()"+"("+self.tree2str(t.right)+")" if t.right else "")else:return str(t.val)+"("+self.tree2str(t.left)+")"+("("+self.tree2str(t.right)+")" if t.right else "")

转载于:https://www.cnblogs.com/learning-c/p/9280596.html

leetcode 关于树的题目相关推荐

  1. LeetCode总结 -- 树的遍历篇

    遍历树的数据结构中最常见的操作. 能够说大部分关于树的题目都是环绕遍历进行变体来解决的. 一般来说面试中遇到树的题目是用递归来解决的, 只是假设直接考察遍历. 那么一般递归的解法就过于简单了. 面试官 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    原文地址:https://www.cnblogs.com/grandyang/p/4606334.html 终于将LeetCode的大部分题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开 ...

  3. python--半自动爬取Leetcode上面的所有题目并转成word打印

    python–半自动爬取Leetcode上面的所有题目并转成word打印 python–半自动爬取Leetcode上面的所有题目并转成word打印 写在前面 代码逻辑 代码结构: 代码流程 具体代码 ...

  4. LeetCode刷题指南——题目精选1

    这是LeetCode经典题目总结文章~ 基础:将数据结构及算法学习的差不多,LeetCode题目按类别刷题及总结,参考鄙人数据结构及算法系列文章~ 按类别将每类题目做好,大概刷250道左右的程度即可. ...

  5. LeetCode 1245. 树的直径(图的最大直径结论)

    文章目录 1. 题目 2. 解题 1. 题目 求树的最大直径. 2. 解题 类似题目:LeetCode 5538. 统计子树中城市之间最大距离(枚举所有可能+图的最大直径) 结论:求无权无向图中的最长 ...

  6. LeetCode——字节跳动系列题目

    转至:https://blog.csdn.net/Uupton/article/details/84640146 今天登陆leetcode发现探索区多了字节跳动的专栏,特意用了一下午去刷,有些是之前刷 ...

  7. java回溯算法_回溯算法讲解--适用于leetcode绝大多数回溯题目

    什么是回溯算法? 回溯法是一种系统搜索问题解空间的方法.为了实现回溯,需要给问题定义一个解空间. 说到底它是一种搜索算法.只是这里的搜索是在一个叫做解空间的地方搜索. 而往往所谓的dfs,bfs都是在 ...

  8. Leetcode动态规划部分典型题目分类及总结

    参考内容 https://leetcode-cn.com/problems/longest-palindromic-substring/solution/zhong-xin-kuo-san-dong- ...

  9. leetcode前缀树java_LeetCode 实现 Trie (前缀树)

    题目大意: 略. 分析: 字典树模板. 代码如下: 1 class Trie { 2 public: 3 int passed; // 记录经过这个节点的字符串数量 4 int ends; // 记录 ...

最新文章

  1. 循环队列,定义循环队列长度为10,编写初始化队列、入队、出队、求队长,实现10,20,30,40,50,60,70,80入队,10,20,30出队,56,67入队的算法功能。
  2. 【AutoML】进化算法如何用于自动模型搜索(NAS)
  3. Android引入library失败的可能原因
  4. c语言中*用于指针,关于C语言中指针的理解
  5. 应付账款账龄分析模板_6万字长文剖析宁德时代(三):财务分析
  6. Character.isLetterOrDigit(ch)判断ch是否为字母或数字
  7. oracle快捷语句框架中,Oracle框架:PL/SQL编程:
  8. 蓝桥杯 算法训练 K好数
  9. 20200717每日一句
  10. LCD显示--TM1640芯片驱动程序
  11. 第10章第13节:使用iSlide的图标库往幻灯片中插入一枚图标 [PowerPoint精美幻灯片实战教程]
  12. 新手试炼:C语言实现加密版2-4阶行列式运算!
  13. c# 中控 触摸精灵_触摸精灵脚本编辑器
  14. 专题2:matlab矩阵处理
  15. ARFoundation从零开始3-创建ARFoundation项目
  16. FastDFS文件同步机制分析
  17. leetcode【135】Candy【c++版,双数组,单数组,坡峰坡谷】
  18. Ubuntu 20.04没有声音播放时出现哒哒的噪音
  19. 海康威视2023届超新星实习生招聘
  20. 第一个计算出地球周长的人——埃拉托色尼

热门文章

  1. oracle中$的用法,关于expdp 中query用法小结
  2. MySQL 优化 —— WHERE 子句优化
  3. MySQL 高级 ———— MySQL逻辑架构图简介
  4. python求出五位数的回文数_python之递归
  5. 数组添加进formdata_javascript – FormData追加数组中的项目
  6. windows下如何在命令行里切换到任意目录
  7. php 的html文件怎么打开,什么是html文件?html格式如何打开?(图)
  8. mysql的存储过程和索引区别_mysql查看索引与存储过程
  9. 经典sql语句50题_SQL面试经典50题:带你从建表开始
  10. matlab数字通信,基于matlab时分复用数字通信系统的设计与实现.pdf