問題
例子
思路
-
方法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;
}
}