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

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

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) {

        List<Integer> prelist = new ArrayList<>();
        List<Integer> inlist = new ArrayList<>();
        List<Integer> postlist = new ArrayList<>();

        preorder(root,prelist);
        inorder(root,inlist);
        postorder(root,postlist);

        int result[][] = new int[3][];
        result[0] = new int[prelist.size()];
        result[1] = new int[inlist.size()];
        result[2] = new int[postlist.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 preorder(TreeNode root, List<Integer> list){
        if (root != null){
            list.add(root.val);
            if (root.left != null){
                preorder(root.left,list);
            }
            if (root.right != null){
                preorder(root.right, list);
            }

        }
    }

    private void inorder(TreeNode root, List<Integer> list){

        if (root != null){
            if (root.left != null){
                inorder(root.left, list);
            }
            list.add(root.val);
            if (root.right != null){
                inorder(root.right, list);
            }        
        }



    }

    private void postorder(TreeNode root, List<Integer> list){

        if (root != null){          
            if (root.left != null){
                postorder(root.left, list);
            }           
            if (root.right != null){
                postorder(root.right, list);
            }           
            list.add(root.val);
        }
    }
}
全部评论

相关推荐

11-26 22:34
已编辑
重庆邮电大学 Java
快手 客户端开发 (n+5)k*16 公积金12
牛客895077908号:佬 什么双非硕啊
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务