LeetCode107:二叉树的层次遍历||

    技术2022-07-20  59

    /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> ans = new ArrayList<>(); while(root==null){ return ans; } Queue<TreeNode> q = new LinkedList<>(); q.add(root); while(!q.isEmpty()){ List<Integer> tem = new ArrayList<>(); int size = q.size(); for(int i = 0 ;i < size;i++){ TreeNode cur = q.poll(); if(cur == null) continue; tem.add(cur.val); if(cur.left!=null){ q.add(cur.left); } if(cur.right!=null){ q.add(cur.right); } } ans.add(0,tem); } return ans; } }

     

    Processed: 0.016, SQL: 9