之字打印树

来源:互联网 发布:浮生一日知乎 编辑:程序博客网 时间:2024/04/30 17:30

import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
 
    public TreeNode(int val) {
        this.val = val;
 
    }
 
}
*/
public class Solution {
    publicArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer> > result=newArrayList<ArrayList<Integer> >();
          if(pRoot==null)return result;
          Stack<TreeNode> s1=newStack<TreeNode>();
          Stack<TreeNode> s2=newStack<TreeNode>();
          s1.push(pRoot);
          TreeNode temp;
          ArrayList<Integer> tArrayList;
          while(!s1.empty()||!s2.empty()){
              tArrayList=newArrayList<Integer>();
              while(!s1.empty()){
                  temp=s1.pop();
                  tArrayList.add(temp.val);
                  if(temp.left!=null)
                      s2.push(temp.left);
                  if(temp.right!=null)
                      s2.push(temp.right);
              }
              if(!tArrayList.isEmpty()){
                  result.add(tArrayList);
              }
              tArrayList=newArrayList<Integer>();
              while(!s2.empty()){
                  temp=s2.pop();
                  tArrayList.add(temp.val);
                  if(temp.right!=null)
                      s1.push(temp.right);
                  if(temp.left!=null)
                      s1.push(temp.left);
              }
              if(!tArrayList.isEmpty()){
                  result.add(tArrayList);
              }
          }
        returnresult;
    }
 
}
    添加笔记
0 0
原创粉丝点击