• lintcode : 二叉树的层次遍历


    题目

    二叉树的层次遍历

    给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)

    样例

    给一棵二叉树 {3,9,20,#,#,15,7} :

      3
     / 
    9  20
      /  
     15   7
    

    返回他的分层遍历结果:

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

    挑战1:只使用一个队列去实现它

    挑战2:用DFS算法来做

    解题 


    队列很容易,先加入,然后取出来的同时加入左右孩子节点

    在剑指offer中有个题目和这个很类似,其只是层次遍历二叉树,没有要求把每层的节点单独放在一起的。

    上面说的规律:每一次打印一个节点的时候,如果该结点有子结点,则把该结点的子结点放到一个队列的尾部。接下来到队列的头部取出最早进入队列的结点。

    重复前面的打印操作,直到队列中所有的结点都被打印出来为止。

    上面是层次打印所有节点,而不是对每一层的节点放在一个list中输出,所以队列保存当前层的元素。

    /**
     * Definition of TreeNode:
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left, right;
     *     public TreeNode(int val) {
     *         this.val = val;
     *         this.left = this.right = null;
     *     }
     * }
     */
     
     
    public class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: Level order a list of lists of integer
         */
        public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
            // write your code here
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            
            ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>();
            if(root == null)
                return tree;
            queue.offer(root);
            while(!queue.isEmpty()){
                ArrayList<Integer> list = new ArrayList<Integer>();
                int size = queue.size();
                for(int i=0;i<size;i++){
                    TreeNode head = queue.poll();
                    list.add(head.val);
                    if(head.left!=null){
                        queue.offer(head.left);
                    }
                    if(head.right!=null){
                        queue.offer(head.right);
                    }
                }
                tree.add(list);
            }
            return tree;
        }
    }
    Java Code

     DFS程序,参见九章

  • 相关阅读:
    IKAnalyzer
    stanford corenlp的TokensRegex
    Linux网络编程-tcp缓存设置
    Java NIO(2):缓冲区基础
    Java NIO(1):迟迟登场的NIO
    git的笔记和使用中的一些技巧的总结
    vagrant 系列 博客
    flutter创建swift kotlin项目
    react eject 命令失败
    react native react-native-vector-icons/Ionicons 出现 Unrecognized font family的错误
  • 原文地址:https://www.cnblogs.com/theskulls/p/5125858.html
Copyright © 2020-2023  润新知