剑指Offer-60.把二叉树打印成多行(C++/Java)

题目:

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

分析:

层次打印二叉树,在打印二叉树结点的同时,保存好结点的左右孩子,不断的重复打印,直到需要打印的数组为空即可。

程序:

C++

class Solution {
public:
    vectorint> > Print(TreeNode* pRoot) {
        if(pRoot == nullptr)
            return res;
        vector printS;
        vector temp;
        printS.push_back(pRoot);
        while(!printS.empty()){
            //vector temp;
            vector<int> resTemp;
            for(auto i:printS){
                if(i->left != nullptr)
                    temp.push_back(i->left);
                if(i->right != nullptr)
                    temp.push_back(i->right);
            }
            for(int i = 0; i < printS.size(); ++i)
                resTemp.push_back(printS[i]->val);
            res.push_back(resTemp);
            printS.swap(temp);
            temp.clear();
        }
        return res;
    }
private:
    vectorint>> res;
};

Java

import java.util.ArrayList;


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

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

    }

}
*/
public class Solution {
    ArrayList > Print(TreeNode pRoot) {
        if(pRoot == null)
            return res;
        ArrayList printS = new ArrayList<>();
        ArrayList temp = new ArrayList<>();
        printS.add(pRoot);
        while(!printS.isEmpty()){
            ArrayList resTemp = new ArrayList<>();
            for(TreeNode i:printS){
                if(i.left != null)
                    temp.add(i.left);
                if(i.right != null)
                    temp.add(i.right);
            }
            for(int i = 0; i < printS.size(); ++i)
                resTemp.add(printS.get(i).val);
            res.add(resTemp);
            printS.clear();
            printS.addAll(temp);
            temp.clear();
            resTemp = null;
        }
        return res;
    }
    private ArrayList> res = new ArrayList>();
}

你可能感兴趣的:(剑指Offer-60.把二叉树打印成多行(C++/Java))