首页 > 每天刷一道牛客题霸-第5天-实现二叉树先序,中序和后序遍历
头像
菜鸟也要飞的高
编辑于 2020-12-02 12:30
+ 关注

每天刷一道牛客题霸-第5天-实现二叉树先序,中序和后序遍历

题目

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362?tpId=190&rp=1&ru=%2Factivity%2Foj&qru=%2Fta%2Fjob-code-high-rd%2Fquestion-ranking

import java.util.*;


public class Solution {
    /**
     *
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    public  static ArrayList<Integer> list;
    public void  pre(TreeNode root){
        if (root != null){
            list.add(root.val);
            pre(root.left);
            pre(root.right);
        }
    }
    public void  mid(TreeNode root){
        if (root != null){

            mid(root.left);
            list.add(root.val);
            mid(root.right);
        }
    }
    public void  last(TreeNode root){
        if (root != null){

            last(root.left);

            last(root.right);
            list.add(root.val);
        }
    }
    public int[][] threeOrders (TreeNode root) {
        list = new ArrayList<>();
        TreeNode node = root;
        pre(node);
        node = root;
        mid(node);
        node = root;
        last(node);

        int[][] resultArray = new int[3][list.size()/3];
        int count = 0;
        for (int i = 0 ; i < 3;i ++){
            for (int j = 0 ; j < list.size() / 3 ; j++){
                resultArray[i][j] = list.get(count);
                count++;
            }
        }
        return resultArray;

        // write code here
    }
}

全部评论

(0) 回帖
加载中...
话题 回帖

相关热帖

近期热帖

近期精华帖

热门推荐