102. Binary Tree Level Order Traversal && 107. Binary Tree Level Order Traversal II

来源:互联网 发布:centos 高可用 编辑:程序博客网 时间:2024/06/04 08:37

Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).

层序遍历,BFS

  public List<List<Integer>> levelOrder(TreeNode root) {        List<List<Integer>> r = new LinkedList<List<Integer>>();        if(root == null) return r;        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();        queue.offer(root);        while(!queue.isEmpty() ){            List<Integer> tmp = new ArrayList<Integer>();            LinkedList<TreeNode> list = new LinkedList<TreeNode>();            while(!queue.isEmpty()){                TreeNode t = queue.poll();                tmp.add(t.val);                if(t.left != null){                    list.offer(t.left);                }                 if(t.right != null){                    list.offer(t.right);                }            }            queue = list;            r.add(tmp);        }        return r;    }
  1. Binary Tree Level Order Traversal II
public class Solution {    public List<List<Integer>> levelOrderBottom(TreeNode root) {        List<List<Integer>> r = new ArrayList<List<Integer>>();        if(root == null) return r;        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();        queue.offer(root);        while(!queue.isEmpty() ){            List<Integer> tmp = new ArrayList<Integer>();            LinkedList<TreeNode> list = new LinkedList<TreeNode>();            while(!queue.isEmpty()){                TreeNode t = queue.poll();                tmp.add(t.val);                if(t.left != null){                    list.offer(t.left);                }                 if(t.right != null){                    list.offer(t.right);                }            }            queue = list;            r.add(0,tmp); //层序遍历加入顺序倒叙        }        return r;    }}
0 0
原创粉丝点击