`

Find Next Node of BST

BST 
阅读更多

Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in a binary search tree. You may assume that each node has a link to its parent. 

public TreeNode findNext(TreeNode node) {
	if(node == null) return null;
	if(node.parent==null || node.right != null) {
		// find left most child in right sub tree
		TreeNode next = node.right;
		while(next.left != null) next = next.left;
		return next;
	} else {
		// go up until we are on the left side of parent node
		TreeNode p = node.parent;
		while(p != null && p.left != node) {
			node = p;
			p = p.parent;
		}
		return p;
	}
}

  

如果没有父节点的话,可以这么做:

public TreeNode findNext(TreeNode root, TreeNode node) {
	if(root == null || node == null) return null;
	if(node.right != null) {
		TreeNode n = node.right;
		while(n.left != null) {
			n = n.left;
		}
		return n;
	}
	TreeNode n = null;
	while(root != null) {
		if(root.val > node.val) {
			n = root;
			root = root.left;
		} else if(root.val < node.val) {
			root = root.right;
		} else {
			break;
		}
	}
	return n;
}

 

Reference:

http://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/

分享到:
评论

相关推荐

    java-leetcode题解之第109题有序链表转换二叉搜索树.zip

    这是一道涉及数据结构与算法的问题,主要涵盖了链表操作和二叉搜索树(BST)的构建。 首先,让我们理解链表和二叉搜索树的基本概念。链表是一种线性数据结构,其中的元素不一定是连续存储的,而是通过指针连接。在...

    Google笔试 要求:体现你使用算法,数据结构解决问题的思路

    题目中的数据结构定义为`struct Node`,包含左右相邻节点指针`lnext`和`rnext`,以及存储值的整型变量`value`。这可能是一个自平衡二叉搜索树的变体,如AVL树或红黑树,或者是一个简单的二叉搜索树。 对于搜索排序...

    通讯录编写实训报告

    每个`Node`结构体还有一个指针成员`Next`,用于链接下一个`Node`,形成一个单链表。另外,定义了一个`struct hNode`结构体,用于保存链表的头指针和记录总数,方便对链表进行操作。 程序提供了多种功能,包括初始化...

    LeetCode最全代码

    389 | [Find the Difference](https://leetcode.com/problems/find-the-difference/) | [C++](./C++/find-the-difference.cpp) [Python](./Python/find-the-difference.py) | _O(n)_ | _O(1)_ | Easy | | ...

    webstorm2019版本创建VUE项目

    enoent This is related to npm not being able to find a file.”指出问题可能在于npm(Node Package Manager)无法找到必要的文件。这可能是由于以下原因: - 没有正确安装或配置Node.js和npm。 - 项目根目录下...

Global site tag (gtag.js) - Google Analytics