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

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

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> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        List<Integer> list3 = new ArrayList<>();

        xianxu(root, list1);
        zhongxu(root, list2);
        houxu(root, list3);

        int[][] res = new int[3][list1.size()];
        for (int i = 0; i < list1.size(); i++) {
            res[0][i] = list1.get(i);
            res[1][i] = list2.get(i);
            res[2][i] = list3.get(i);
        }
        return res;
    }

    private void xianxu(TreeNode root, List<Integer> list){
        if (root == null) {
            return;
        }
        list.add(root.val);
        xianxu(root.left, list);
        xianxu(root.right, list);
    }

    private void zhongxu(TreeNode root, List<Integer> list){
        if (root == null) {
            return;
        }
        zhongxu(root.left, list);
        list.add(root.val);
        zhongxu(root.right, list);
    }

    private void houxu(TreeNode root, List<Integer> list){
        if (root == null) {
            return;
        }
        houxu(root.left, list);
        houxu(root.right, list);
        list.add(root.val);
    }

}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务