classSolution{ List<List<Integer>> levels = new ArrayList<List<Integer>>();
publicvoidhelper(TreeNode node, int level){ // start the current level if (levels.size() == level) levels.add(new ArrayList<Integer>());
// fulfil the current level levels.get(level).add(node.val);
// process child nodes for the next level if (node.left != null) helper(node.left, level + 1); if (node.right != null) helper(node.right, level + 1); }
public List<List<Integer>> levelOrder(TreeNode root) { if (root == null) return levels; helper(root, 0); return levels; } }
classSolution{ public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> levels = new ArrayList<List<Integer>>(); if (root == null) return levels;
Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); int level = 0; while ( !queue.isEmpty() ) { // start the current level levels.add(new ArrayList<Integer>());
// number of elements in the current level int level_length = queue.size(); for(int i = 0; i < level_length; ++i) { TreeNode node = queue.remove();
// fulfill the current level levels.get(level).add(node.val);
// add child nodes of the current level // in the queue for the next level if (node.left != null) queue.add(node.left); if (node.right != null) queue.add(node.right); } // go to next level level++; } return levels; } }
TreeNode x = new TreeNode("x"); TreeNode y = new TreeNode("y"); TreeNode a = new TreeNode("a"); TreeNode b = new TreeNode("b"); TreeNode c = new TreeNode("c");
xx.left = x; x.parent = xx;
x.left = a; a.parent = x;
x.right = y; y.parent = x;
y.left = b; b.parent = y;
y.right = c; c.parent = y;
x = TreeUtil.leftRotate(x); x = TreeUtil.rightRotate(x);