有两种思路:
- 每次都把节点存入一个变量中,相当于前驱节点,当下次遍历的时候如果前驱节点和目标节点的值相等,那么我们需要的就是当前的节点。注意的是,要创建两个变量,一个存结果,一个存前驱节点。否则直接返回前驱节点的话会导致如果下一个节点为空,他也会返回一个节点,而不是我们期盼的null。
- 设置一个flag,当当前节点和目标节点值相等的时候我们让flag为true。下一次遍历,当flag为true的时候返回当前节点。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode pre;
TreeNode res;
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
dfs(root,p);
return res;
}
public void dfs(TreeNode root,TreeNode p){
if(root == null) return;
dfs(root.left,p);
if(pre != null && res == null){ //这里千万注意 res == null 的意思是 只给res赋值一次。否则他在回溯的过程会不断的赋值 覆盖。
if(pre.val == p.val){
res = root;
return;
}
}
pre = root;
dfs(root.right,p);
}
}
一开始没有res == null 那 结果如下
虽然知道为啥不对 但是我还是纳闷为啥结果不是6.经过debug调试发现原因是因为在判断里面赋值后就return了没有进入5的右节点。