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

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

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) {
        if (root == null)
        {
            return null;
        }
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();

        // 先序
        stack.push(root);
        while (!stack.isEmpty())
        {
            TreeNode node = stack.pop();
            if (node != null)
            {
                list.add(node.val);
                stack.push(node.right);
                stack.push(node.left);
            }
        }
        int[] pre = new int[list.size()];
        for (int i = 0; i < pre.length; i++)
        {
            pre[i] = list.get(i);
        }
        list.clear();

        // 中序
        TreeNode curr = root;
        while (!stack.isEmpty() || curr != null)
        {
            if (curr == null)
            {
                curr = stack.pop();
                list.add(curr.val);
                curr = curr.right;
            }
            else
            {
                stack.push(curr);
                curr = curr.left;
            }
        }
        int[] mid = new int[list.size()];
        for (int i = 0; i < mid.length; i++)
        {
            mid[i] = list.get(i);
        }
        list.clear();

        // 后序
        stack.push(root);
        while (!stack.isEmpty())
        {
            TreeNode node = stack.pop();
            if (node != null)
            {
                list.add(node.val);
                stack.push(node.left);
                stack.push(node.right);
            }
        }
        int[] pos = new int[list.size()];
        for (int i = 0, j = pos.length - 1; i < pos.length; i++, j--)
        {
            pos[i] = list.get(j);
        }

        // output 
        int[][] ans = new int[3][];
        ans[0] = pre;
        ans[1] = mid;
        ans[2] = pos;
        return ans;
    }
}
全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
05-19 15:21
已编辑
门头沟学院 Java
白火同学:你才沟通了200,说实话,北上广深杭这里面你连一座城市的互联网公司都没投满呢,更别说还有各种准一线二线城市了。等你沟通突破了三位数,还没结果再考虑转行的事吧。
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-08 14:08
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

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