1.题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
2.算法描述
3
种
情
况
:
3种情况:
3种情况:
1.
当
前
结
点
存
在
右
子
树
,
那
么
中
序
遍
历
中
当
前
结
点
的
下
一
个
结
点
是
其
右
子
树
中
最
左
端
的
结
点
。
1.当前结点存在右子树,\red{那么中序遍历中当前结点的下一个结点是其右子树中最左端的结点}。
1.当前结点存在右子树,那么中序遍历中当前结点的下一个结点是其右子树中最左端的结点。
2.
当
前
结
点
不
存
在
右
子
树
,
如
果
这
个
结
点
位
于
整
棵
树
的
左
子
树
上
,
那
么
中
序
遍
历
中
当
前
结
点
的
2.当前结点不存在右子树,如果这个结点位于整棵树的左子树上,\red{那么中序遍历中当前结点的}
2.当前结点不存在右子树,如果这个结点位于整棵树的左子树上,那么中序遍历中当前结点的
下
一
个
结
点
是
其
父
节
点
的
父
节
点
。
\red{下一个结点是其父节点的父节点。}
下一个结点是其父节点的父节点。
3.
当
前
结
点
不
存
在
右
子
树
,
如
果
这
个
结
点
位
于
整
棵
树
的
右
子
树
上
,
则
中
序
遍
历
中
当
前
结
点
不
存
在
下
一
个
结
点
。
3.当前结点不存在右子树,如果这个结点位于整棵树的右子树上,\red{则中序遍历中当前结点不存在下一个结点。}
3.当前结点不存在右子树,如果这个结点位于整棵树的右子树上,则中序遍历中当前结点不存在下一个结点。
3.代码描述
3.1.Java代码
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode 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){//假设 当前结点位于树的左子树上
TreeLinkNode p = pNode.next;//那么中序遍历中当前结点的下一个结点是其父节点的父节点(简称爷爷结点)
if(p.left == pNode)//爷爷结点的左子树是父亲结点
return p;
pNode = pNode.next;
}
//否则当前结点 必然在树的右子树上
return null;
}
}
3.2.Python代码
# -*- coding:utf-8 -*-
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
def GetNext(self, pNode):
if not pNode:
return None
if pNode.right:
pNode = pNode.right
while pNode.left:
pNode = pNode.left
return pNode
while pNode.next:
p = pNode.next
if p.left == pNode:
return p
pNode = pNode.next
return None