随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-05-03 23:35

题目链接

原题:

For a given node in binary search tree find a next largest number in search tree.

题目:给定一个二叉搜索树的节点,找出此节点在树中的中序后继节点,也就是比它大的最小节点。

解法:右子树向左走到底,左祖先走到顶向右。草稿纸上一画图就清楚了。

代码:

复制代码
 1 // http://www.careercup.com/question?id=5205167846719488
 2 struct TreeNode {
 3     int val;
 4     TreeNode *left;
 5     TreeNode *right;
 6     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
 7 };
 8 
 9 class Solution {
10 public:
11     int nextLargestNumber(TreeNode *root, int val) {
12         if (root == nullptr) {
13             // nothing to do
14             return val;
15         }
16         
17         left_top = nullptr;
18         return findRecursive(root, val);
19     }
20 private:
21     TreeNode *left_top;
22     
23     int findRecursive(TreeNode *root, int val) {
24         if (root == nullptr) {
25             // not found, return val
26             return val;
27         } else if (root->val > val) {
28             left_top = root;
29             return findRecursive(root->left, val);
30         } else if (root->val < val) {
31             return findRecursive(root->right, val);
32         } else {
33             if (left_top == nullptr) {
34                 // val is the greatest of all.
35                 return val;
36             }
37             if (root->right == nullptr) {
38                 return left_top->val;
39             }
40             
41             left_top = root->right;
42             while (left_top->left != nullptr) {
43                 left_top = left_top->left;
44             }
45             return left_top->val;
46         }
47     };
48 }
复制代码

 

 posted on   zhuli19901106  阅读(152)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示