• 二叉树的前序遍历


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

    递归:

    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;
    }
  • 相关阅读:
    LeetCode 50: Pow(x, n)
    Codility 1: equilibrium
    LeetCode 49: Anagrams
    crackme160--(5)
    crackme160--(4)
    魔兽显血改键工具的脱壳和修改
    crackme160--(3)
    crackme160--(1)
    python-装饰器
    编程语言C++01-C++入门学习路线
  • 原文地址:https://www.cnblogs.com/earthhouge/p/11262901.html
Copyright © 2020-2023  润新知