[leetcode] 285. Inorder Successor in BST 解题报告
2016-03-14 14:39
771 查看
题目链接: https://leetcode.com/problems/inorder-successor-in-bst/
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return
思路: 一种较为通用的方法是中序遍历一遍二叉树,记录结点的前一个结点,这样当前一个结点为p时,当前结点就是p的后继结点.这种方法适用于一般二叉树,时间复杂度为O(n).
但是这种方法并没有利用到二叉搜索树的性质. 因此我们还可以比较给定结点与根结点的大小, 如果根节点的值较大, 说明这个结点在根节点的左边, 因此此时根节点就是其不紧切后继, 然后再往左子树去比较. 如果根节点值较小, 说明我们要找的结点在根节点右边.这样一步步就可以找到最终的后继.
各自代码如下:
1.
2.
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return
null.
思路: 一种较为通用的方法是中序遍历一遍二叉树,记录结点的前一个结点,这样当前一个结点为p时,当前结点就是p的后继结点.这种方法适用于一般二叉树,时间复杂度为O(n).
但是这种方法并没有利用到二叉搜索树的性质. 因此我们还可以比较给定结点与根结点的大小, 如果根节点的值较大, 说明这个结点在根节点的左边, 因此此时根节点就是其不紧切后继, 然后再往左子树去比较. 如果根节点值较小, 说明我们要找的结点在根节点右边.这样一步步就可以找到最终的后继.
各自代码如下:
1.
/** * 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: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if(!root) return root; inorderSuccessor(root->left, p); if(pre == p) ans = root; pre = root; inorderSuccessor(root->right, p); return ans; } private: TreeNode *pre = NULL, *ans = NULL; };
2.
/** * 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: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) { if(!root || !p) return NULL; TreeNode* ans = NULL; while(root) { if(root->val > p->val) { ans = root; root = root->left; } else root = root->right; } return ans; } };第二种参考: https://leetcode.com/discuss/86078/sharing-my-36ms-c-solution
相关文章推荐
- Mysql压测工具mysqlslap 讲解
- BPMN 2.0 rendering toolkit and web modeler | bpmn.io
- MemoryCache
- const volatile
- Linux基础回顾之基础命令二
- intellij idea 快捷键-不定时更新
- 源码编译安装 MySQL 5.5.x 实践
- 欢迎使用CSDN-markdown编辑器
- JavaScript学习笔记——基本包装类型(上)Boolean、Number
- 使用闭包实现显示隐藏div
- 查看Data Guard同步--使用Broker
- 配置网络策略中的 NAP 条件
- 【分布式计算】关于Hadoop、Spark、Storm的讨论
- Android中使用DownloadManager进行下载操作
- 简述raid0、raid1、raid5的区别
- Android布局学习笔记
- 国家语言的简称编码
- 【C++ STL学习之四】Map类模板
- 亲密接触Redis-第三天(Redis的Load Balance)
- 文档内的当前编码不能正确保存文档内所有字符,可能需改为UTF-8支持的编码