Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/littlehaes/article/details/91384502
welcome to my blog
Offer surface prove safety questions 8 (java version): the next node of the binary tree
Title Description
And wherein a given binary tree of a node, find the next node in a preorder traversal order and returns. Note that the node in the tree contains not only the left and right child nodes, the parent node contains a pointer pointing to
Thinking
- To find out preorder
- Specific ideas See note
the complexity
- Time complexity: depth and number of relevant
- Space complexity: not allocated extra space, O (1)
/*
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.当前节点有右子树,则下一个节点是右子树中最左子节点
2.当前节点没有右子树
2.1当前节点有父节点
2.1.1当前节点是其父节点的左子节点, 则下一个节点是当前节点的父节点
2.1.2当前节点是其父节点的右子节点, 当前节点的父节点记作p
2.1.2.1向上遍历p的父节点,直到找到这样一个节点, 该节点是其父节点的左子节点
2.1.2.2向上遍历p的父节点,如果遇到null,则说明当前节点是最后一个节点,没有下一个节点
2.2当前节点没有父节点
说明当前节点是最后一个节点, 没有下一个节点了, 返回null
可以看出,上面总共有2大类情况
*/
//1.
if(pNode.right != null){
TreeLinkNode curr = pNode.right;
while(curr.left != null){
curr = curr.left;
}
return curr;
}
//2.1
if(pNode.next != null){
TreeLinkNode curr = pNode.next;
//2.1.1
if(pNode == curr.left)
return curr;
//2.1.2 (包括了2.1.2.1和2.1.2.2)
TreeLinkNode father = curr.next;
while(father != null && curr == father.right ){
curr = father;
father = curr.next; //如果father是null了, 则while判断中的father.right就会报错,所以需要扩充while中的条件
}
return father;
}
//2.2
return null;
}
}