Print all nodes according to binary tree first order, middle order and post order respectively

Title description
Print all nodes according to binary tree first order, middle order and post order respectively.

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整型二维数组
     */
    // 用list集合存储元素
    List<Integer> pre = new ArrayList<>();
    List<Integer> mid = new ArrayList<>();
    List<Integer> nex = new ArrayList<>();
    public int[][] threeOrders(TreeNode root) {
    
    
        // write code here
        preOrder(root);
        midOrder(root);
        nexOrder(root);
        int len = pre.size();
        int[][] arr = new int[3][len];
        
        for (int i = 0; i < len; i++) {
    
    
            arr[0][i] = pre.get(i);
        }
        for (int i = 0; i < len; i++) {
    
    
            arr[1][i] = mid.get(i);
        }
        for (int i = 0; i < len; i++) {
    
    
            arr[2][i] = nex.get(i);
        }  
        return arr;
        
    }
    // 前序遍历
        public void preOrder(TreeNode root) {
    
    
            if (root != null) {
    
    
                pre.add(root.val);
                preOrder(root.left);
                preOrder(root.right);
                
            }
        }

        // 中序遍历
        public void midOrder(TreeNode root) {
    
    
            if (root != null) {
    
    
                 midOrder(root.left);
                mid.add(root.val);
                midOrder(root.right);
            }
        }

        // 后序遍历
        public void nexOrder(TreeNode root) {
    
    
            if (root != null) {
    
    
                nexOrder(root.left);
                nexOrder(root.right);
                nex.add(root.val);
            } 
        }
}

Guess you like

Origin blog.csdn.net/qq_43518425/article/details/114832639