zoukankan      html  css  js  c++  java
  • 二叉树的前序遍历

    二叉树前序遍历,分为递归方法和非递归方法:

    递归:

    private static List<Integer> preList = new ArrayList<>();
    public static List<Integer> preorderTraversalRec(TreeNode root){
        if (null == root){
            return preList;
        }
        preorder(root);
        return preList;
    }
    private static void preorder(TreeNode root){
        if (null == root){
            return;
        }
        preList.add(root.val);
        preorder(root.left);
        preorder(root.right);
    }

    非递归:

    public static List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (null == root){
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            list.add(node.val);
            if (null != node.right){
                stack.push(node.right);
            }
            if (null != node.left){
                stack.push(node.left);
            }
        }
        return list;
    }
  • 相关阅读:
    登录注册功能
    29-----BBS论坛
    linux笔记
    nginx,uwsgi发布web服务器
    linux常用服务部署
    linux系统基础优化及常用命令
    linux基本操作命令
    linux命令
    linux基础
    阿里云服务器搭建
  • 原文地址:https://www.cnblogs.com/earthhouge/p/11262901.html
Copyright © 2011-2022 走看看