《剑指offer》78--把二叉树打印成多行[C++][Java]

把二叉树打印成多行_牛客题霸_牛客网【牛客题霸】收集各企业高频校招笔面试题目,配有官方题解,在线进行百度阿里腾讯网易等互联网名企笔试面试模拟考试练习,和牛人一起讨论经典试题,全面提升你的技术能力icon-default.png?t=LBL2https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tags=&title=&difficulty=0&judgeStatus=0&rp=1

题目描述

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

解题思路

【C++解法】

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector > Print(TreeNode* pRoot) {
        vector< vector> res;
        queue q;
        if(pRoot) q.push(pRoot);
        while(!q.empty()) {
            int len = q.size();
            vector tmp(len);
            for(int i=0; ileft) q.push(p->left);
                if(p->right) q.push(p->right);
                tmp[i] = p->val;
            }
            res.push_back(tmp);
        }
        return res;
    }
};

【Java解法】

import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
/*
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) {
        ArrayList > res = new ArrayList > ();
        Queue q = new LinkedList<>();
        if (pRoot != null) {q.add(pRoot);}
        while (!q.isEmpty()) {
            ArrayList tmp = new ArrayList<>();
            int len = q.size();
            while (len-- > 0) {
                TreeNode p = q.poll();
                if (p.left != null) {q.add(p.left);}
                if (p.right != null) {q.add(p.right);}
                tmp.add(p.val);
            }
            res.add(tmp);
        }
        return res;
    }
}

参考文献

【1】Java 实例 – 队列(Queue)用法 | 菜鸟教程

你可能感兴趣的:(剑指offer,算法,散列表,leetcode)