• Careercup


    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 }
  • 相关阅读:
    C#界面交互Invoke的便捷写法
    C#简单线程同步例子
    输出一个数据库中所有表的数据量
    JavaScript 解析xml字符串
    图片与Byte流互转
    html中name 和 id 的区别
    JavaScript 解析xml文件
    关于序列化的使用
    js 动态创建xml串
    js动态删除节点
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3705820.html
Copyright © 2020-2023  润新知