树的前序遍历方法

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

递归

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;

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值