1.题目
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
2.思路
- 当前节点存在右子树,它下个节点是它当前节点的右节点的左节点的左节点的左节点。。。。
- 当前节点不存在右子树:
(1)若当前结点为其父结点的左子结点时,其下一个结点为其父结点;
(2)若当前结点为其父结点的右子结点时,继续向上遍历父结点的父结点的 父节点的。。。,直到找到一个结点是其父结点的左子结点,该结点即为下一结点。
如图二叉树中序遍历结果为:d b e h i a f c w q g y
- c节点,存在右子树它的右节点g的左节点q
- d节点,不存在右子树,它的下个节点为b
- i节点,不存在右子树,它的下个节点为a,为它 父节点h的 父节点 的 父节点b的 父节点a
3.代码实现
public class Solution {
class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
//指向该节点父节点的指针
TreeLinkNode parent = null;
TreeLinkNode(int val) {
this.val = val;
}
}
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.parent != null) {
if (pNode.parent.left == pNode) {
return pNode.parent;
}
pNode = pNode.parent;
}
return null;
}