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

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

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

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整型二维数组
 * 就是写了三道简单题,二叉树前序中序后序遍历
 */
public int[][] threeOrders (TreeNode root) {
    // write code here
    preorder(root, list1);
    inorder(root, list2);
    afterorder(root, list3);
    
    int n = list1.size();
    int[][] arr = new int[3][n];
    for(int i = 0; i < n; i++){
        arr[0][i] = list1.get(i);
        arr[1][i] = list2.get(i);
        arr[2][i] = list3.get(i);
    }
    return arr;
}
List<Integer> list1 = new ArrayList<>();
public void preorder(TreeNode root, List<Integer> list){
    if(root == null) return;
    list1.add(root.val);
    preorder(root.left, list);
    preorder(root.right, list);
}
List<Integer> list2 = new ArrayList<>();
public void inorder(TreeNode root, List<Integer> list){
    if(root == null) return;
    inorder(root.left, list);
    list2.add(root.val);
    inorder(root.right, list);
}
List<Integer> list3 = new ArrayList<>();
public void afterorder(TreeNode root, List<Integer> list){
    if(root == null) return;
    afterorder(root.left, list);
    afterorder(root.right, list);
    list3.add(root.val);
}

}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 11:22
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-10 15:58
投个小米提前批试试水,先投一个岗位看看形势,不行就再沉淀一下投第二个岗位,莫辜负
Java抽象带篮子:我嘞个骚刚,已经开始研发6g了吗
投递小米集团等公司7个岗位
点赞 评论 收藏
分享
05-14 20:34
门头沟学院 Java
窝补药贝八股:管他们,乱说,反正又不去,直接说680
点赞 评论 收藏
分享
06-25 16:25
梧州学院 Java
愿汐_:项目介绍那么长,然而你做了啥就一句话?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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