剑指Offer——二叉树的下一个节点
1、题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
2、代码实现
/*
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;
}
//1、如果一个节点有右子树那么它的下一个节点就是它的右子树中的最左节点。
if (pNode.right != null) {
TreeLinkNode node = pNode.right;
while (node.left != null) {
node = node.left;
}
return node;
}
//2、如果节点是它父节点的左子节点,那么它的下一个节点就是它的父节点
//3、如果一个节点既没有右子树,而且它还是它父节点的右子节点,我们可以沿着指向父节点的指针一直向上
//遍历,直到找到一个是它父节点的左子节点的节点,如果这个节点存在的话,那么这个节点的父节点就是
//我们要找的下一个节点
while (pNode.next != null) {
if (pNode.next.left == pNode) {
return pNode.next;
}
pNode = pNode.next;
}
return null;
}
}
浙公网安备 33010602011771号