今天这个题算是给我巩固了一下中序遍历
一、本题还是使用两种方法,递归和迭代
1.递归:分为左遍历,右遍历,中遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
ArrayList<TreeNode> list=new ArrayList<>();
void f(TreeNode root){
if(root==null){
return;
}
f(root.left);//递归先遍历左边
list.add(root);
f(root.right);//右边
}
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
f(root);
for(int i=0;i<list.size()-1;i++){
if(list.get(i)==p){//寻找到了指定值,
return list.get(i+1);//给出后面的数据
}
}
return null;
}
}
递归比较好理解,不过对空间复杂度是树的深度次方复杂
二、迭代遍历
1.首先呢,看不懂这个的请看我的中序遍历题解
2.我们提前把当前节点用TreeNode a存起来
3.,下一次循环a==p成立,就输出当前值:t,
4.因为我的判断时上一次的节点是否等于p,等于的话就输出这一次的节点,按照题目要求输入p的下一次节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
TreeNode cont=stack.pop(),a=null;
while(cont!=null||!stack.isEmpty()){
while(cont!=null){
stack.push(cont);
cont=cont.left;
}
TreeNode t=stack.pop();
if(a==p){//判断
return t;
}
a=t;
cont=t.right;
}
return null;
}
}