微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

02_二叉搜索树_求一个节点的前驱与后继节点

1.前驱节点:中序遍历时的前一个节点

如果是二叉搜索树,前驱节点就是前一个比它小的节点,即肯定是左子树的部分

  • 1.node.left != null,则其前驱节点是左子树中的最大那个,即左子树的右孩子的右孩子…right == null
  • 2.node.left == null &&node.parent != null,那么其前驱节点是其父节点的父节点,直到需要考虑的节点已经为parent的右子树
  • 3.node.leftnull== && node.parent ==null,则没有前驱节点为空

    在这里插入图片描述

	protected Node<E> predecessor(Node<E> node) {
		if (node == null) return null;

		// 前驱节点在左子树当中(left.right.right.right....)
		Node<E> p = node.left;
		if (p != null) {
			while (p.right != null) {
				p = p.right;
			}
			return p;
		}
		
		// 从父节点、祖父节点中寻找前驱节点
		// 考虑父节点不为空 且 该节点为父节点的左子树
		while (node.parent != null && node == node.parent.left) {
			node = node.parent;
		}
		/**
		 * 不符合的时候是以下两种情况
		 * node.parent == null---->返回null
		 * node == node.parent.right---->返回父节点即node.parent
		 * 所以返回 node.parent
 		 */
		return node.parent;
	}

2.后继节点:中序遍历时的后一个节点

如果是二叉搜索树,后继节点就是后一个比它大的节点,即肯定是右子树的部分,即前驱节点左取右,右取左即可

在这里插入图片描述

	protected Node<E> successor(Node<E> node) {
		if (node == null) return null;
		
		// 前驱节点在左子树当中(right.left.left.left....)
		Node<E> p = node.right;
		if (p != null) {
			while (p.left != null) {
				p = p.left;
			}
			return p;
		}
		
		// 从父节点、祖父节点中寻找后继节点
		while (node.parent != null && node == node.parent.right) {
			node = node.parent;
		}

		return node.parent;
	}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐