首页 > 代码库 > LeetCode 107. Binary Tree Level Order Traversal II

LeetCode 107. Binary Tree Level Order Traversal II

题意:给你个二叉树,要求按深度下到上,输出每行的整数。

 

我的思路:我采用了广度优先搜索,并利用两个变量,来计算当前所遍历的深度,然后就把每个深度的整数都加入到容器里,一旦深度+1 就把该容器添加到总容器里。

 

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {        public List<List<Integer>> levelOrderBottom(TreeNode root) {        return bfs(root);    }        private List<List<Integer> > bfs(TreeNode root) {        List<List<Integer> > ans = new ArrayList<>();        if (root == null) return ans;                Queue<TreeNode> Q = new LinkedList<TreeNode>();        Q.add(root);                TreeNode endRight = root;     //记录当前深度最右边的节点        TreeNode currentRight = null; //记录当前遍历的节点中最右边的孩子节点                List<Integer> list = new ArrayList<>();                while (!Q.isEmpty()) {            TreeNode t = Q.poll();            list.add(t.val);                        if(t.left != null) {                Q.add(t.left);                currentRight = t.left;            }            if(t.right != null) {                Q.add(t.right);                currentRight = t.right;            }            if(t == endRight) {   //如果当前节点等于当前深度最右边的节点,那么深度就要+1了                endRight = currentRight;                ans.add(0, list);                list = new ArrayList<>();            }        }        return ans;    }}

  

LeetCode 107. Binary Tree Level Order Traversal II