剑指Offer--二叉树的下一个节点(JS)

题目描述

给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

思路:

1. 二叉树为空,返回null
2. 右子树存在,返回右子树的最左节点
3. 节点不是根节点。是父节点的左孩子,则返回父节点;否则向上去遍历父节点的父节点,重复之前的判断,返回结果。

/*function TreeLinkNode(x){
    this.val = x;
    this.left = null;
    this.right = null;
    this.next = null;
}*/
function GetNext(pNode){
	if(pNode==null){
		return null
	}
	if(pNode.right!=null){
		pNode=pNode.right;
		while(pNode.left!=null){
			pNode=pNode.left;
		}
		return pNode
	}
	while(pNode.next!=null){
		let pRoot=pNode.next;
		if(pRoot.left===pNode){
			return pRoot
		}
		pNode=pNode.next;
	}
	return null
}
发布了69 篇原创文章 · 获赞 52 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_38983511/article/details/103000355