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