zoukankan      html  css  js  c++  java
  • *Binary Tree Level Order Traversal

    题目

    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,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its level order traversal as:

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

    题解
    这道题就是用传统的BFS来做。代码如下:

    public class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) 
        {
            List<List<Integer>> res = new LinkedList<List<Integer>>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            if(root==null) return res;
            queue.add(root);
            while(!queue.isEmpty())
            {
                int levelnum = queue.size(); //这层有几个TreeNode
                List<Integer> sublist = new LinkedList<Integer>();
                for(int i=0; i<levelnum;i++)
                {
                    TreeNode node = queue.poll();
                    if(node.left!=null) queue.add(node.left);
                    if(node.right!=null) queue.add(node.right);
                    sublist.add(node.val);
                }
                res.add(sublist);
            }
            return res;   
        }
    }
     

    注意:

    广度优先算法用queue,先进先出。

    入queue用add:Appends the specified element to the end of this list. This method is equivalent to addLast(E).

    出queue用poll:Retrieves and removes the head (first element) of this list.

    也可以用pop

    深度优先算法:用stack,先进后出。

    入stack用push:Pushes an element onto the stack represented by this list. In other words, inserts the element at the front of this list. This method is equivalent to addFirst(E).

    出stack用pop:Pops an element from the stack represented by this list. In other words, removes and returns the first element of this list. This method is equivalent to removeFirst().

    二者都可以用linkedlist定义,只是使用的时候methods不同,来决定是先进先出,还是先进后出。引用JDK API中关于LinkedList的一句说明:"These operations allow linked lists to be used as a stack, queue, or double-ended queue."由此,可以得知,使用LinkedList可以轻松的实现栈和队列的功能。通过查看LinkedList源码实现,发现其底层采用双向链表实现。

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

    reference:http://www.cnblogs.com/springfor/p/3891391.html

  • 相关阅读:
    [LeetCode][JavaScript]Copy List with Random Pointer
    [LeetCode][JavaScript]Best Time to Buy and Sell Stock II
    [LeetCode][JavaScript]Best Time to Buy and Sell Stock
    [LeetCode][JavaScript]Populating Next Right Pointers in Each Node
    [LeetCode][JavaScript]Text Justification
    [LeetCode][JavaScript]LRU Cache
    用CRTP在C++中实现静态函数的多态
    C++的静态分发(CRTP)和动态分发(虚函数多态)的比较
    用Y分钟学会X
    看看你能认出多少种编程语言
  • 原文地址:https://www.cnblogs.com/hygeia/p/4704027.html
Copyright © 2011-2022 走看看