题目描述
参考
思路
主要根据中序遍历二叉树的特点:
代码
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
/*
思路:根据二叉树的中序遍历特点:
1、如果二叉树当前节点有右子树,那么返回的是当前节点的右子树的左子树
2、如果当前节点无右子树(pNode=pNode.next.left),返回当前节点的父节点
*/
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode==null) {return null;}
//1、如果二叉树当前节点有右子树,那么返回的是当前节点的右子树的左子树
if(pNode.right!=null){
pNode = pNode.right;
while(pNode.left!=null){
pNode = pNode.left;
}
return pNode;
}
//2、如果当前节点无右子树,返回当前节点的父节点
while(pNode.next!=null){
if(pNode.next.left==pNode){ //注意理解
return pNode.next;
}
pNode = pNode.next;
}
//3 题目中其实最后一个中序遍历的节点是null的
return null;
}
}
原文:https://www.cnblogs.com/jiyongjia/p/13377412.html