Binary Tree Level Order Traversal II

Binary Tree Level Order Traversal II

问题:

Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

思路:

  层次遍历 BFS 

我的代码:

public class Solution {

    public List<List<Integer>> levelOrderBottom(TreeNode root) {

        List<List<Integer>> rst = new ArrayList<List<Integer>>();

        if(root == null) return rst;

        

        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        queue.offer(root);

        while(!queue.isEmpty())

        {

            int size = queue.size();

            List<Integer> list = new ArrayList<Integer>();

            for(int i = 0; i < size; i++)

            {

                TreeNode node = queue.poll();

                list.add(node.val);

                if(node.left != null)

                    queue.offer(node.left);

                if(node.right != null)

                    queue.offer(node.right);

            }

            rst.add(list);

        }

        Collections.reverse(rst);

        return rst;

    }

}
View Code

他人代码:

public class Solution {

    public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {

        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();



        if (root == null) {

            return result;

        }



        Queue<TreeNode> queue = new LinkedList<TreeNode>();

        queue.offer(root);

        int currLevelNodeNum = 1;

        int nextLevelNodeNum = 0;



        while (currLevelNodeNum != 0) {

            ArrayList<Integer> currLevelResult = new ArrayList<Integer>();

            nextLevelNodeNum = 0;



            while (currLevelNodeNum != 0) {

                TreeNode node = queue.poll();



                currLevelNodeNum--;

                currLevelResult.add(node.val);



                if (node.left != null) {

                    queue.offer(node.left);

                    nextLevelNodeNum++;

                }



                if (node.right != null) {

                    queue.offer(node.right);

                    nextLevelNodeNum++;

                }

            }



            result.add(0, currLevelResult);

            currLevelNodeNum = nextLevelNodeNum;

        }

        return result;

    }

}
View Code

学习之处:

  • ArrayList竟然还有这个add(index,Object)功能,如此便省去了翻转链表的时间,插入表头的时间O(n),翻转链表的时间O(n),实际的程序运行时间也一致。

你可能感兴趣的:(binary)