美文网首页
69. 二叉树的层次遍历

69. 二叉树的层次遍历

作者: 叨逼叨小马甲 | 来源:发表于2017-12-05 00:08 被阅读0次

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

    给一棵二叉树 {3,9,20,#,#,15,7} :
    
      3
     / \
    9  20
      /  \
     15   7
    
    返回他的分层遍历结果:
    
    [
      [3],
      [9,20],
      [15,7]
    ]
    

    代码

    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    
    import LintClass.TreeNode;
    
    /**
     * 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 LevelOrder_69 {
        /*
         * @param root: A Tree
         * @return: Level order a list of lists of integer
         */
        public List<List<Integer>> levelOrder(TreeNode root) {
            // write your code here
            if(root == null)
                return null;    
            
            List<List<Integer>> output = new ArrayList<List<Integer>>();
            LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            queue.add(root);
            TreeNode temp = null;
            while (!queue.isEmpty()) {
                ArrayList<Integer> resultArray = new ArrayList<Integer>();
                int size = queue.size();
                for(int i = 0; i < size; i++){
                    temp = queue.poll();
                    resultArray.add(temp.val);
                    if (temp.left != null) {
                        queue.add(temp.left);
                    }
                    if (temp.right != null) {
                        queue.add(temp.right);
                    }
                }
                output.add(resultArray);
            }
            
            return output;
        }
        
        public static void main(String[] args) {
            TreeNode root = new TreeNode(3);
            TreeNode root_1_left = new TreeNode(9);
            TreeNode root_1_right = new TreeNode(20);
            TreeNode root_2_left = new TreeNode(15);
            TreeNode root_2_right = new TreeNode(7);
            root.left = root_1_left;
            root.right = root_1_right;
            root.right.left = root_2_left;
            root.right.right = root_2_right;
            LevelOrder_69 obj = new LevelOrder_69();
            System.out.print(obj.levelOrder(root));
        }
    }
    

    相关文章

      网友评论

          本文标题:69. 二叉树的层次遍历

          本文链接:https://www.haomeiwen.com/subject/orzfixtx.html