Java -- 树的先序、中序、后序遍历

这篇博客介绍了如何使用Java实现二叉树的先序、中序和后序遍历,并将遍历结果转换为整型二维数组。通过定义TreeNode类,然后分别实现firstOrder、middleOrder和thenOrder三个静态方法进行不同顺序的遍历。最后,将ArrayList转换为int数组并返回结果。
摘要由CSDN通过智能技术生成
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    private static ArrayList<Integer> first = new ArrayList<>();
    private static ArrayList<Integer> middle = new ArrayList<>();
    private static ArrayList<Integer> then = new ArrayList<>();
    
    private static void firstOrder(TreeNode root){
        if(root != null){
            first.add(root.val);
            firstOrder(root.left);
            firstOrder(root.right);
        }
    }
    
    private static void middleOrder(TreeNode root){
        if(root!=null){
            middleOrder(root.left);
            middle.add(root.val);
            middleOrder(root.right);
        }
    }
    
    private static void thenOrder(TreeNode root){
        if(root!=null){
            thenOrder(root.left);
            thenOrder(root.right);
            then.add(root.val);
        }
    }
    
    private static int[] toIntArray(ArrayList<Integer> arrayList){
        int[] intArray = arrayList.stream().mapToInt(Integer::valueOf).toArray();
        return intArray;
    }
    
    public int[][] threeOrders (TreeNode root) {
        // write code here
        int[][] orders= new int[3][];
        firstOrder(root);//调用先序方法
        orders[0] = toIntArray(first);//将先序遍历的结果放入二维数组中
        middleOrder(root);//调用中序方法
        orders[1] = toIntArray(middle);//将后序遍历
        thenOrder(root);
        orders[2] = toIntArray(then);
        return orders;
    }
}

int[] intArray = arrayList.stream().mapToInt(Integer::valueOf).toArray();的解析
https://blog.csdn.net/weixin_49428831/article/details/120732178

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值