zoukankan      html  css  js  c++  java
  • 剑指Offer-60.把二叉树打印成多行(C++/Java)

    题目:

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

    分析:

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

    程序:

    C++

    class Solution {
    public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            if(pRoot == nullptr)
                return res;
            vector<TreeNode*> printS;
            vector<TreeNode*> temp;
            printS.push_back(pRoot);
            while(!printS.empty()){
                //vector<TreeNode*> 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:
        vector<vector<int>> 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<ArrayList<Integer> > Print(TreeNode pRoot) {
            if(pRoot == null)
                return res;
            ArrayList<TreeNode> printS = new ArrayList<>();
            ArrayList<TreeNode> temp = new ArrayList<>();
            printS.add(pRoot);
            while(!printS.isEmpty()){
                ArrayList<Integer> 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<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
    }
  • 相关阅读:
    弹性盒模型的实际应用
    大图滚动--这是精髓实例
    三级联动
    sql
    jsp2
    marquee
    人机五子棋(AI算法有瑕疵)
    Jsp1
    倒计时
    时间
  • 原文地址:https://www.cnblogs.com/silentteller/p/12115190.html
Copyright © 2011-2022 走看看