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

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

https://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
	  //集合分别保存三种遍历结果
        ArrayList<Integer> list1=new ArrayList<>();
        ArrayList<Integer> list2=new ArrayList<>();
        ArrayList<Integer> list3=new ArrayList<>();
	  //前中后遍历
        pre(root,list1);
        mid(root,list2);
        post(root,list3);
	  //数组进行保存
        int arr[][]=new int[3][list1.size()];
	  //将集合元素添加到数组
        for(int i=0;i<list1.size();i++){
            arr[0][i]=list1.get(i);
            arr[1][i]=list2.get(i);
            arr[2][i]=list3.get(i);
        }
        return arr;
    }
  //前序
    public void pre(TreeNode root,ArrayList<Integer> list){
        if(root==null){
            return;
        }
        list.add(root.val);
        pre(root.left,list);
        pre(root.right,list);
    }
  //中序
    public void mid(TreeNode root,ArrayList<Integer> list){
        if(root==null){
            return;
        }
        mid(root.left,list);
        list.add(root.val);
        mid(root.right,list);
    }
  //后序
    public void post(TreeNode root,ArrayList<Integer> list){
        if(root==null){
            return;
        }
        post(root.left,list);
        post(root.right,list);
        list.add(root.val);
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
点赞 评论 收藏
分享
哥_留个offer先:跟他说,你这个最好用c#,微软就用c#Java不适合这个项目
点赞 评论 收藏
分享
xdm怎么说&nbsp;要被拷打了&nbsp;担心是KPI
丹田:面就完了,就当日薪四位数的大佬免费给给你面试。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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