题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    public int[][] threeOrders (TreeNode root) {
        // write code here
        List<Integer> preList = new ArrayList<>();
        List<Integer> inList = new ArrayList<>();
        List<Integer> postList = new ArrayList<>();

        pre(root, preList);
        in(root, inList);
        post(root, postList);

        int[][] result = new int[3][preList.size()];

        for (int i = 0; i < preList.size(); i++) {
            result[0][i] = preList.get(i);
            result[1][i] = inList.get(i);
            result[2][i] = postList.get(i);
        }

        return result;
    }


    private void pre(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }

        list.add(root.val);
        pre(root.left, list);
        pre(root.right, list);
    }

    private void in(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }

        in(root.left, list);
        list.add(root.val);
        in(root.right, list);
    }

    private void post(TreeNode root, List<Integer> list) {
        if (root == null) {
            return;
        }

        post(root.left, list);
        post(root.right, list);
        list.add(root.val);
    }


}

全部评论

相关推荐

04-25 19:29
已编辑
宁波大学 测试开发
被普调的六边形战士很高大:你我美牛孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务