[Leetcode 102]Binary Tree Level Order Traversal (Medium)

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

For example:

Given binary tree [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7

return its level order traversal as:

[
  [3],
  [9,20],
  [15,7]
]

BFS

思路1

  1. 用Queue来存每个level的节点,每次取queue当前size个节点,放入result,同时将当前节点的左右子树放入queue。
  2. 循环停止条件,queue为空

思路2

  1. 分别用两个Queue来存当前层和下一层level的节点。先将root push into Queue1, 当Queue1 or Queue2 is not empty时,循环执行 step 2 and 3
    • step 2. 取Queue1中所有的节点,并放入layer中;同时把节点的左右子节点放入Queue2。 当Queue1为空时,表示当前层全部遍历完成,结果加入result
    • step 3. Queue1为空后,swap Queue1 & Queue2, 并将Queue2置空。又重新进入循环,直到Queue1 && Queue2 are empty

One Queue

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {  
    public List> levelOrder(TreeNode root) {
        List> result = new ArrayList<>();
        
        if (root == null) {
            return result;
        }
        
        Queue queue = new LinkedList();
        queue.add(root);
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            List layer = new ArrayList<>();
            for (int i = 0; i < size; i++){
                TreeNode curNode = queue.poll();
                layer.add(curNode.val);
                if (curNode.left != null) {
                    queue.add(curNode.left);
                }
                if (curNode.right != null) {
                    queue.add(curNode.right);
                }
            }
            result.add(layer);
        }
        return result;
    }
}

Two Queue

class Solution {
    public List> levelOrder(TreeNode root) {
        List> result = new ArrayList<> ();
        if (root == null) {
            return result;
        }
        
        Queue  tracker1 = new LinkedList <> ();
        Queue  tracker2 = new LinkedList <> ();
        tracker1.offer (root);
        
        while (!tracker1.isEmpty () || !tracker2.isEmpty ()) {
            List layer = new ArrayList<> ();
            while (!tracker1.isEmpty ()) {
                TreeNode current = tracker1.poll ();
                layer.add (current.val);
                
                if (current.left != null) {
                    tracker2.offer (current.left);
                }
                
                if (current.right != null) {
                    tracker2.offer (current.right);
                }
            }
            
            if (tracker1.isEmpty ()) {
                result.add (new ArrayList<> (layer));
            }
            tracker1 = tracker2;
            tracker2 = new LinkedList <> ();
        }
        
        return result;
    }
}

你可能感兴趣的:([Leetcode 102]Binary Tree Level Order Traversal (Medium))