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

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

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


/*
 * 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
        List<Integer> listA=new ArrayList<>();
        List<Integer> listB=new ArrayList<>();
        List<Integer> listC=new ArrayList<>();
        //先序遍历
        prePrint(root,listA);
        //中序遍历
        MiddlePrint(root,listB);
        //后序遍历
        AfterPrint(root,listC);
        
        int[][] arr =new int[3][listA.size()];
        for(int i=0;i<listA.size();i++){
            arr[0][i]=listA.get(i);
            arr[1][i]=listB.get(i);
            arr[2][i]=listC.get(i);
        }
        
        return arr;
    }
    //先序遍历
    public void prePrint(TreeNode root,List<Integer> list){
        if(root==null){
            return ;
        }
        list.add(root.val);
        prePrint(root.left,list);
        prePrint(root.right,list);
    }
    //中序遍历
    public void MiddlePrint(TreeNode root,List<Integer> list){
        if(root==null){
            return ;
        }
        
        MiddlePrint(root.left,list);
        list.add(root.val);
        MiddlePrint(root.right,list);
    }
    //后序遍历
    public void AfterPrint(TreeNode root,List<Integer> list){
        if(root==null){
            return ;
        }
        
        AfterPrint(root.left,list);
        AfterPrint(root.right,list);
        list.add(root.val);
        
    }
    
}
全部评论

相关推荐

求个付费实习岗位:这种就是吃满时代红利又没啥技术水平,只能靠压力学生彰显优越感的老登,别太在意了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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