java Programming Problem Print Binary Tree from Top to Bottom

  • 2021-07-01 07:26:13
  • OfStack

This article example for everyone to share java from top to bottom to print out 2-tree specific code, for your reference, the specific content is as follows

github: Sword refers to all the test questions of offer programming


import java.util.ArrayList;
import java.util.Stack;


/**
 * 
 *  Sword finger offer Programming problem ( JAVA Realization ) -No. 1 22 Question: Print from top to bottom 2 Fork tree 
 * 
 *  Title description 
 *  Print from top to bottom 2 Each node of the cross tree, the nodes in the same layer are printed from left to right. 
 *
 */
public class Test22 {

 ArrayList<Integer> arrayList = new ArrayList<>();
 //  Each layer is stacked in turn 
 Stack<TreeNode> stack1 = new Stack<>();
 //  From stack1 Elements out of the stack are added in turn stack2 , unified 1 Pass stack2 Find their word nodes and press them in stack1
 Stack<TreeNode> stack2 = new Stack<>();

 public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {

 if (root == null) {
 return arrayList;//  Empty returns 
 }
 stack1.push(root);
 while (!stack1.isEmpty()) {
 while (!stack1.isEmpty()) {
 TreeNode tmp = stack1.pop();
 arrayList.add(tmp.val);
 stack2.push(tmp);
 }
 while (!stack2.isEmpty()) {
 TreeNode tmp2 = stack2.pop();
 //  Print from left to right, so the right subtree goes to the stack first 
 if (tmp2.right != null) {
 stack1.push(tmp2.right);
 }
 if (tmp2.left != null) {
 stack1.push(tmp2.left);
 }
 }
 }

 return arrayList;

 }

 public class TreeNode {
 int val = 0;
 TreeNode left = null;
 TreeNode right = null;

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

 }
 }

}
// Other methods 
/**
public class Solution {
 public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
  ArrayList<Integer> list = new ArrayList<Integer>();
  if(root == null) return list;
  Deque<TreeNode> deque = new LinkedList<TreeNode>();
  
  deque.add(root);
  while(!deque.isEmpty()){
  TreeNode t = deque.pop();
  list.add(t.val);
  if(t.left != null) deque.add(t.left);
  if(t.right != null) deque.add(t.right);
  }
  return list;
 }
}
*/


Related articles: