二叉树三序迭代遍历(Java)

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

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

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型二维数组
     */
    public int[][] threeOrders (TreeNode root) {
        // write code here
        int[][] res = new int[3][];
        res[0] = toIntArray(preorder(root));
        res[1] = toIntArray(inorder(root));
        res[2] = toIntArray(postorder(root));
        return res;
    }

    //将List转换为整型数组
    int[] toIntArray(List<Integer> list){
        int[] res = list.stream().mapToInt(Integer::intValue).toArray();
        return res;
    }

    //preorder
    List<Integer> preorder(TreeNode root)
    {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stk = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stk.isEmpty()){
            while(cur != null){
                res.add(cur.val);
                stk.push(cur);
                cur = cur.left;
            }
            cur = stk.pop();
            cur = cur.right;
        }
        return res;
    }

    //inorder
    List<Integer> inorder(TreeNode root)
    {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stk = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stk.isEmpty()){
            while(cur != null){
                stk.push(cur);
                cur = cur.left;
            }
            cur = stk.pop();
            res.add(cur.val);
            cur = cur.right;
        }
        return res;
    }

    //postorder
    List<Integer> postorder(TreeNode root)
    {
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stk = new Stack<>();
        TreeNode cur = root;
        while(cur != null || !stk.isEmpty()){
            while(cur != null){
                res.add(0, cur.val);
                stk.push(cur);
                cur = cur.right;
            }
            cur = stk.pop();
            cur = cur.left;
        }
        return res;
    }
}
全部评论

相关推荐

09-29 17:44
已编辑
蔚来_测(准入职员工)
//鲨鱼辣椒:见不了了我实习了四个月上周再投筛选了一天就给我挂了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务