最佳節點 二叉樹,劍指 Offer II 056 二叉搜索樹中兩個節點之和

 2023-12-25 阅读 28 评论 0

摘要:Problem Description 給定一個二叉搜索樹的 根節點 root 和一個整數 k , 請判斷該二叉搜索樹中是否存在兩個節點它們的值之和等于 k 。假設二叉搜索樹中節點的值均唯一。 Example AC Code class Solution { public:bool findTarget(TreeNode* root, int k) {unordered_set<

Problem Description

給定一個二叉搜索樹的 根節點 root 和一個整數 k , 請判斷該二叉搜索樹中是否存在兩個節點它們的值之和等于 k 。假設二叉搜索樹中節點的值均唯一。

Example

在這里插入圖片描述

AC Code

class Solution {
public:bool findTarget(TreeNode* root, int k) {unordered_set<int> ret;TreeNode *curr=root;stack<TreeNode*> st;while(!st.empty()||curr!=NULL){while(curr!=NULL){st.push(curr);curr=curr->left;}curr=st.top();st.pop();if(ret.count(k-curr->val)) return true;ret.insert(curr->val);curr=curr->right;}return false;}
};

在這里插入圖片描述

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/194711.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息