栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

BM23 二叉树的前序遍历

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

BM23 二叉树的前序遍历


解题思路:二叉树的前序遍历为根左右,很明显要用递归,先保存根节点的值,然后继续保存左孩子的值,然后才是右孩子的值,整个下来需要遍历整个二叉树,然后将保存的值list转成数组返回即可,时间复杂度O(n),空间复杂度O(n)

import java.util.*;



public class Solution {
    

    public int[] preorderTraversal (TreeNode root) {
        // write code here
        ArrayList list = new ArrayList<>();
        addToList(root, list);
        int size = list.size();
        int[] array = new int[size];
        for (int i = 0; i < size; i++) {
            array[i] = list.get(i);
        }
        return array;
    }

    private void addToList(TreeNode root, ArrayList list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        addToList(root.left, list);
        addToList(root.right, list);
    }
}

也可以用java8的stream流来将list转数组返回

import java.util.*;



public class Solution {
    

    public int[] preorderTraversal (TreeNode root) {
        // write code here
        ArrayList list = new ArrayList<>();
        addToList(root, list);
        int[] array = list.stream().mapToInt(x->x).toArray();
        return array;
    }

    private void addToList(TreeNode root, ArrayList list) {
        if (root == null) {
            return;
        }
        list.add(root.val);
        addToList(root.left, list);
        addToList(root.right, list);
    }
}

扩展:也可以使用非递归的方式来实现

import java.util.*;



public class Solution {
    

    public int[] preorderTraversal (TreeNode root) {
        // write code here
        if (root == null) {
            return new int[0];
        }
        ArrayList list = new ArrayList<>();
        Stack stack = new  Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            //根先弹出
            TreeNode node = stack.pop();
            list.add(node.val);
            //先压右节点,因为栈是先进后出
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        int[] array = list.stream().mapToInt(x->x).toArray();
        return array;
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/782789.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号