递归
package com.cbx;
import com.cbx.LeetCode.树.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* @Author:cbx
* @Date:2020/10/27/11:25
*/
public class preOrder {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
preorder(root, res);
return res;
}
public void preorder(TreeNode root, List<Integer> res) {
if (root == null) {
return;
}
res.add(root.val);
preorder(root.left, res);
preorder(root.right, res);
}
}
利用栈
思想:首先保存各节点,然后访问左节点,如果不为空继续访问左节点,如果为空就去访问右节点。。。。依次迭代
public List<Integer> noRecur(TreeNode root){
List<Integer> res=new ArrayList<>();
if (root==null) return res;
Deque<TreeNode> stack=new ArrayDeque<>();
while (root!=null||!stack.isEmpty()){
if (root!=null){
//一直往左进行遍历
res.add(root.val);
stack.push(root);
root=root.left;
}else {
TreeNode value = stack.removeFirst();
root=value.right;
}
}
return res;
}
morris遍历
- 当前节点为cur
- 1.如果cur无左孩子,cur向右移动(cur=cur.right)
- 2.如果cur有左孩子,找到cur左子树上的最右边节点,记为mostRight
- 1)如果mostRight的right指针指向空,让它指向cur,cur向左移动(cur=cur.left)
- 2)如果mostRight的right指针指向cur,让它指向空,cur向右移动(cur=cur.right)
public static List<Integer> morrisPre(TreeNode head){
List<Integer> res=new ArrayList<>();
if (head==null) return res;
TreeNode cur=head;
TreeNode mostRight=null;
while (cur!=null){
mostRight=cur.left;
//左子树不为空,就指向左子树的最右节点
if (mostRight!=null){
while (mostRight.right!=null&&mostRight.right!=cur){
mostRight=mostRight.right;
}
if (mostRight.right==null){
mostRight.right=cur;
res.add(cur.val);
cur=cur.left;
continue;
}else {
mostRight.right=null;
}
}else {
res.add(cur.val);
}
cur=cur.right;
}
return res;
}

本文介绍二叉树的前序遍历方法,包括递归实现、利用栈的非递归实现及Morris遍历。递归实现简单直观;非递归方法使用栈结构进行迭代;Morris遍历则通过改变树结构减少额外空间开销。
328

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



