刷leetcode碰到了二叉树的中序遍历,提供了三种方法,在这里记录一下。
- 常规的递归方法
public List<Integer> inorderTraversal_1(TreeNode root){
List<Integer> res = new ArrayList<Integer>();
recursion(res,node);
return node;
}
public void recursion(List<Integer> res,TreeNode node){
if(node!=null){
recursion(res,node.left);
res.add(node.val);
recursion(res,node.right);
}
}
- 常规的栈储存方法
public List<Integer> inorderTraversal_2(TreeNode root){
List<Integer> res = new ArrayList<Integer>();
Stack<TreeNode> stack =new Stack<TreeNode>();
while(root!=null || !stack.isEmpty()){
//先把左边的全部放进去
while(root!=null){
stack.push(root);
root=root.left;
}
//取出最左边的
root = stack.pop();
res.add(root.val);
//再放入右边的
//两种情况:
// 1. 有右孩子,将右孩子和右孩子的所有左子树放入stack
// 2. 没有右孩子,将root变为null,就不会走里层开头的while,
// 防止将root循环放入
root = root.right;
}
}
- 特别的Morrirs方法
public List<Integer> inorderTraversal_3(TreeNode root){
List<Integer> res = new ArrayList<Integer>();
TreeNode = temp;//临时变量
while(root!=null){
if(root.left!=null){
temp = root.left;
while(temp.right!=null && temp.right != root){
temp = temp.right;
}
// 将右孩子与root相连
//这样“已经到了最左边,没有左孩子”的情况(即下方的while)
//root=root.right可以直接返回上层的根节点
if(temp.right == null){
temp.right = root;
root = root.left;
}else{
// 说明已经连过了,并且下面的树已经走完
// 只有走完了,才会由root = root.right再次返回到这个节点
//首先将连接消除,然后将值加入列表,最后访问右孩子
temp.right = null;
res.add(root.val);
root = root.right;
}
}else{
res.add(root.val);
root = root.right;
}
}
}
1753




被折叠的 条评论
为什么被折叠?



