Find next node in bst
来源:互联网 发布:js打开无导航栏新窗口 编辑:程序博客网 时间:2024/05/23 19:32
碰到过好几次,interview常考高频题,面宝石家的时候这道题当时跪的很彻底,在小哥各种题目下才勉强写出来。
其实大意就是找inorder traversal 里下一个,但是不需要得到所有inorder 结果
geeksforgeek
(1)有parent指针
在cc150上有很好的讲解
三种情况:
i 当前node的right != null, 则返回leftmost of right subtree
ii 当前node.right == null
如果node为其parent的左孩子,则可以直接返回node.parent
如果node为其parent右孩子,则一直向上走直到node在parent left subtree
public TreeNode findNext(TreeNode node){if(node == null) return null;//has right childif(node.right != null){//find leftmost of right childTreeNode tmp = node.right;while(tmp.left != null){tmp = tmp.left;}return tmp;}else{//no right child//if is right child of its parent return the topest gradparent(go up)/* * 8 * / * 5 * \ * 6 * \ * 7 */TreeNode q = node;TreeNode p = node.parent;while(p != null && p.left != q){ // move two pointer upq = p;p = p.parent;}//else is left child of its parents or reach topest return parentreturn p;}}
(2) 没有parent指针
其实唯一不同的就是找parent或者gradparent那部分,这时候我们需要直到这棵树的root,从上向下遍历,记录parent
code下回更新。
0 0
- Find next node in bst
- Find Next Node in InOrder Traverse
- Delete node in BST
- Next Larger Value in BST
- Ch4.5: find the (in-order tranversely) successor of a node in BST.
- Delete Node in a BST
- Delete Node in a BST
- Delete Node in a BST
- leetcode450Delete Node in a BST
- Q4.6 find the ‘next’ node
- closest node to the target in BST
- Closest node to the target in BST
- Add, Search, Delete Node in BST.
- [LeetCode]Delete Node in a BST
- [hard]450. Delete Node in a BST
- 450. Delete Node in a BST
- LeetCode 450. Delete Node in a BST
- 450. Delete Node in a BST
- [Leetcode]Longest Consecutive Sequence
- UVA - 10891(sum游戏,dp)
- 嵌入式linux学习笔记一--打补丁
- *LeetCode-Binary Search Tree Iterator
- 使用Vim配置一个高效的PHP开发环境
- Find next node in bst
- 项目管理的主要控制因素(转)
- 从汇编语言角度看C语言代码,理解计算机如何工作
- *LeetCode- Sum Root to Leaf Numbers
- kvm虚拟化技术实战记录(1)——配置kvm
- [Leetcode] Jump Game
- Spring之AOP模块
- 【输入外挂】
- Math.round(11.5)等於多少? Math.round()