把二叉树打印成多行

2020-07-24  本文已影响0人  Crazy_Bear
import java.util.*;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {
    ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        if(pRoot==null) return res;
        Queue<TreeNode> q = new LinkedList<>();
        ArrayList<Integer> tmp = new ArrayList<>();
        int cur = 1;
        int next =0;
        q.add(pRoot);
        while(!q.isEmpty()){
          TreeNode node = q.remove();
          tmp.add(node.val);
          cur--;
          if(node.left != null) {
              q.add(node.left);
              next++;
          }
          if(node.right != null){
              q.add(node.right);
              next++;
          }
            if(cur==0){
                res.add(new ArrayList<Integer>(tmp));
                tmp.clear();
                cur = next;
                next = 0;
            }
        }
        return res;
    }
    
}
/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int>> res;
            vector<int> res_line;
            queue<TreeNode*> tmp;
            queue<int> height;
            int pre=1;
            if(pRoot==NULL) return {};
            
            tmp.push(pRoot);
            height.push(1);
            while(!tmp.empty())
            {
                if(height.front()==pre) 
                  res_line.push_back(tmp.front()->val);
                else
                {
                    res.push_back(res_line);
                    res_line.clear();
                    res_line.push_back(tmp.front()->val);
                }
                if(tmp.front()->left) 
                {
                    tmp.push(tmp.front()->left);
                    height.push(height.front()+1);
                }
                 if(tmp.front()->right) 
                {
                    tmp.push(tmp.front()->right);
                    height.push(height.front()+1);
                }
                pre=height.front();
                tmp.pop();
                height.pop();
            }
             res.push_back(res_line);
            return res;     
        }
};
上一篇 下一篇

猜你喜欢

热点阅读