leetcode 关于树的题目

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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/570657.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

基于类的访问权限

一个方法可以访问所属类的所有对象的私有数据 class MyClass{public MyClass(String name){this.name name;}private String name;public boolean equals(MyClass other){return name.equals(other.name); } } 转载于:https://www.cnblogs.com/chenzida/p/9285989.html

双击程序后系统弹框“您无权访问此程序”的解决办法

xp下&#xff1a;我的电脑>工具>文件夹选项>查看&#xff0c;勾掉使用简单文件共享选项。如下图&#xff1a; 此时&#xff0c;在右键点击程序图标时&#xff0c;选项卡中会出现“安全”选项卡。如下图&#xff1a; 修改everyone为Administrator...并设置完全控制权限…

adb常用操作命令

1、adb devices 查看当前链接设备&#xff0c;列出连接到计算机的Android设备或者模拟器 2、adb install <apk文件路径> 安装软件 3、adb uninstall <软件名> 卸载apk之前要先查看报名&#xff1a; 知晓包名之后&#xff0c;就可以运用命令卸载该APK 4、adb shell …

让vs编写的程序在未安装vs的电脑上使用的一种方法

今天编了一个每隔10分钟就弹出一个网页的程序&#xff0c;为的是用来投票。代码如下: #include "stdafx.h" #include <iostream> #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { int i0; while(i0) { ShellExecute(NULL, "open&…

轻量级ORM框架 【Dapper】 的使用

ORM是什么&#xff1f; 从字面理解&#xff0c;O是Object&#xff0c;对象&#xff1b;R是Relation&#xff0c;关系&#xff1b;M是Mapping&#xff0c;映射。所以&#xff0c;用一句话概括就是&#xff1a;ORM是一种对象关系映射的技术。 Dapper 是.NET下的一种ORM框架。 Dap…

系统提示一个程序正在被另一个程序调用,如何知道是被哪个程序调用

今天在处理一个病毒时&#xff0c;发现病毒文件无法复制。于是利用processxp找到了病毒文件是被哪个文件调用&#xff0c;然后用md关闭了调用句柄后成功复制文件。具体情况如下&#xff1a; 为了找到是哪个程序调用了befsvc.exe&#xff0c;打开processexplorer.exe&#xff0c…

JS实现文本框不可编辑

方法1: οnfοcusthis.blur() 当鼠标放不上就离开焦点 <input type"text" name"input1" value"中国" οnfοcusthis.blur()> 方法2:readonly <input type"text" name"input1" value"中国" readonly>…

通过修改explorer.exe内存隐藏文件及注册表项

记录今天分析的一个隐藏自身及注册表项的病毒。 1.概述&#xff1a; &#xff08;1&#xff09;此病毒文件为路径为&#xff1a;C:\Windows7\4D525EC1C14.exe&#xff0c;且注册了自启动项&#xff1a; HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run […

WPF xaml中列表依赖属性的定义

WPF xaml中列表依赖属性的定义 原文:WPF xaml中列表依赖属性的定义列表内容属性 如上图&#xff0c;是一个列表标题排序控件&#xff0c;我们需要定义一个标题列表&#xff0c;从而让调用方可以自由的设置标题信息。 在自定义控件时&#xff0c;会遇到列表依赖属性&#xff0c;…

由于权限问题无法删除注册表键值的解决方法

在中了某个病毒之后手动删除病毒自启动项失败&#xff0c;如下图&#xff1a; 查看run项的权限&#xff0c;发现用户被修改成了Everyone&#xff0c;并且没有任何权限&#xff0c;如下图&#xff1a; 手动赋予Everyone用户完全控制权限后删除注册表项成功&#xff0c;如下图&am…

ELK篇---------elasticsearch集群安装配置

说明&#xff1a;本次ELK的基础配置如下&#xff1a;虚拟机&#xff1a;vmware 11系统&#xff1a;centos7.2 两台IP&#xff1a;172.16.1.15/16一、下载eswget https://download.elastic.co/elasticsearch/release/org/elasticsearch/distribution/zip/elasticsearch/2.1.0/e…

c# 常用基本函数

1、去除字符串中的所有空格 /// <summary> /// 去除字符串中的所有空格 /// </summary> /// <param name"originalStr"></param> /// <returns></returns> internal static string Tr…

c++利用windows api遍历指定文件夹及其子文件夹中的文件

以下代码在vs2008中测试通过&#xff0c;利用FindFirstFile,FindNextFile函数遍历了我电脑上全路径为“C:\\Users\\v_tianboli\\Desktop\\windows程式设计开发指南”的文件夹&#xff0c;并输出文件夹及子文件夹中的所有文件完整路径到控制台。完整代码如下&#xff1a; #inclu…

如何获取用户当前详细的地理位置

如何获取用户当前详细的地理位置 一、总结 一句话总结&#xff1a;第三方API和js中geolocation。 1、google地图API教程地址&#xff1f; Google API 教程 | 菜鸟教程http://www.runoob.com/googleapi/googleapi-tutorial.html 或者直接百度 google地图中文api 二、如何获取用户…

某释放驱动的样本分析及手杀报告

此为样本文件下载链接&#xff1a;http://download.csdn.net/detail/cs08211317dn/3982364&#xff0c;压缩包解压缩密码为&#xff1a;virus。 今天花了1个多小时分析了一款名为123.exe的病毒&#xff0c;觉得挺有意思的&#xff0c;于是顺手写个手杀报告&#xff0c;以备以后…

CentOS 7.2 安装zabbix 3.4

一、zabbix版本选择及部署环境说明 1、zabbix版本选择 zabbix官网地址&#xff1a;www.zabbix.com zabbix每半年发布一个长期支持版&#xff0c;目前长期支持版有2.0、3.0等&#xff0c;所以选择zabbix版本建议选择长期支持版&#xff0c;除非有特殊需求。 2、部署环境环境说明…

吴恩达机器学习笔记(二) —— Logistic回归

主要内容&#xff1a; 一.回归与分类 二.Logistic模型即sigmoid function 三.decision boundary 决策边界 四.cost function 代价函数 五.梯度下降 六.自带求解函数 七.多分类问题 一.回归与分类 回归&#xff1a;用于预测&#xff0c;输出值是连续型的。例如根据房子的大小预测…

弹出选择文件夹的对话框 BROWSEINFO 的用法【MFC】

以下是在vs2008中编译通过的代码&#xff0c;代码注释详细。要实现的功能是点击“浏览”按钮&#xff0c;即弹出选择文件夹的对话框。并将选择的文件夹或文件路径显示在MessageBox中。 void CMFC_TrojanKillerDlg::OnBnClickedButton1() {// TODO: 在此添加控件通知处理程序代码…

HDU 3709 Balanced Number(数位DP)题解

思路&#xff1a; 之前想直接开左右两边的数结果爆内存... 枚举每次pivot的位置&#xff0c;然后数位DP&#xff0c;如果sum<0返回0&#xff0c;因为已经小于零说明已经到了pivot右边&#xff0c;继续dfs只会越来越小&#xff0c;且dp数组会炸 注意一下一些细节&#xff1a;…

regini.exe使用方法

创建一个名称test 类型reg_dword 数据1 如果是只有那会默认以类型reg_sz创建 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ys test reg_dword 1 2。注册表键数值 [更改的权限] 例如: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run…