The binary print offer 60. prove safety in a plurality of rows

The binary print offer 60. prove safety in a plurality of rows

topic

Printing the binary tree in layers from top to bottom, from left to right with the output layer node. Each line of output layer.

Thinking

And on a similar topic, but you do not need to use two stacks, and only need to queue to store can be, is simply traverse the level, remember to set a mark to record the length of each line, because it is the row output.

Code

  public class TreeNode {

    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
      this.val = val;

    }

  }

  ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {

    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
    if (pRoot == null) {
      return ans;
    }
    Queue<TreeNode> queue = new LinkedList<>();
    ArrayList<Integer> list = new ArrayList<>();
    queue.add(pRoot);
    int start = 0, end = 1;
    while (!queue.isEmpty()) {
      TreeNode cur = queue.remove();
      list.add(cur.val);
      start++;
      if (cur.left != null) {
        queue.add(cur.left);
      }
      if (cur.right != null) {
        queue.add(cur.right);
      }
      if (start == end) {
        end = queue.size();
        start = 0;
        ans.add(list);
        list = new ArrayList<>();
      }
    }
    return ans;
  }

Guess you like

Origin www.cnblogs.com/blogxjc/p/12426159.html