问题
例子
思路
-
方法1
-
方法2
1: 如果该结点有右子树,则返回右子树最深的左子树
2:如果该结点没有右子树,不断向上找该结点的父结点。
2.1:如果存在某个父节点,是其父节点的左子树,则返回其父节点
2.2:如果不存在某个父节点,是其父节点的左子树,则返回null
代码
//方法1
import java.util.*;
public class Solution {
private TreeLinkNode res = null;
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
TreeLinkNode node = pNode;
while(node.next!=null) {
node = node.next;
}
TreeLinkNode root=node;
midOrder(root,pNode);
return res;
}
public void midOrder(TreeLinkNode root, TreeLinkNode node) {
if(root==null) return;
if(root.left!=null) midOrder(root.left,node);
if(root!=node && node.val<=root.val) {
//只找第一个满足条件的,此时res为null
if(res==null) {
res=root;
}
return;
}
if(root.right!=null) midOrder(root.right,node);
}
}
//方法2
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode==null) return null;
if(pNode.right!=null) {
TreeLinkNode node = pNode.right;
while(node.left!=null) {
node=node.left;
}
return node;
}
while(pNode.next!=null) {
if(pNode.next.left==pNode) return pNode.next;
pNode = pNode.next;
}
return null;
}
}