• 102. 二叉树的层次遍历


    递推

    package leetcode;
    
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Queue;
    
    class TreeNode {
    	int val;
    	TreeNode left;
    	TreeNode right;
    
    	TreeNode(int x) {
    		val = x;
    	}
    }
    
    class Solution {
    	public List<List<Integer>> levelOrder(TreeNode root) {
    		List<List<Integer>> ls = new ArrayList<List<Integer>>();
    		Queue<TreeNode> queue = new LinkedList<TreeNode>();
    
    		if (root == null)
    			return ls;
    
    		queue.add(root);
    		while (!queue.isEmpty()) {				                            	 // 结合数学运算
    			int len = queue.size();
    			List<Integer> l = new ArrayList<Integer>();
    			for (int i = 0; i < len; i++) {                                                        //len用于记录queue.size() 不会被for 里面的代码所影响  这道题 很妙
    				TreeNode T = queue.poll();
    				
    				if (T.left != null)
    					queue.add(T.left);
    				if (T.right != null)
    					queue.add(T.right);
    
    				l.add(T.val);
    			}
    			ls.add(l);
                             
    		}
    		return ls;
    	}
    }
    

    解法二

    递归

    class Solution {
        public List<List<Integer>> levelOrder(TreeNode root) {
            List<List<Integer>> list = new ArrayList<>();
            levelOrder(root, list, 0);
            return list;
        }
        
        public void levelOrder(TreeNode root, List<List<Integer>> list, int level){
            if(root != null){
                if(level > list.size() - 1){
                    List<Integer> nodes = new ArrayList<>();
                    list.add(nodes);
                }
                list.get(level).add(root.val);
                levelOrder(root.left, list, level + 1);
                levelOrder(root.right, list, level + 1);
            }
        }
    }
    
  • 相关阅读:
    Android控件之圆形Button
    MotionEvent常见值
    Android通过URL加载网络图片
    Android音频播放实例
    Android沉浸式任务栏的实现
    Android学习之路书籍推荐
    Linux端BaiduPCS-Go使用方法
    Remove Duplicates from Sorted ListII
    RemoveDuplicatesfromSortedList
    Partition List 划分链表
  • 原文地址:https://www.cnblogs.com/cznczai/p/11180921.html
Copyright © 2020-2023  润新知