这几天由于一些原因没及时更新博客,抽时间来写写数据结构。
这次是去寻找二叉树的下一个节点。
总体思路最开始依旧是递归,但是比较困难,因此还是来画图分析。
节点有指向父节点的指针next,节点类为:
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
中序遍历是按照 左 根 右 的规律来遍历的。
也就是如果指向1节点,这个时候发现1节点右子树不为空,那就遍历右子树,找到3发现有左子树,则依次沿着左子树走到最左,这里用循环去走:
pNode = pNode.right;
while(pNode.left != null)
{
pNode = pNode.left;
}
由于中序遍历的特点,我们不用考虑左子树,只用考虑有没右子树存在。
接下来考虑右子树不存在的情况,如果指向4节点。那就要循环去左上移动。移动到该节点为一个左子树的根(如果存在),就返回这个父节点。否则返回为空:
while(pNode.next != null)
{
if(pNode.next.left == pNode) return pNode.next;
pNode = pNode.next;
}
如果是左子树,下一个节点就是该父节点,这种情况已经包含在上面的代码里。
整个过程完整实现为:
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)
{
if(pNode.next.left == pNode)
{
return pNode.next;
}
pNode = pNode.next;
}
return null;