102. 二叉樹的層序遍歷

題意

給你一個(gè)二叉樹,請(qǐng)你返回其按 層序遍歷 得到的節(jié)點(diǎn)值。 (即逐層地,從左到右訪問所有節(jié)點(diǎn))。

示例:
二叉樹:[3,9,20,null,null,15,7],

3

/
9 20
/
15 7
返回其層序遍歷結(jié)果:

[
[3],
[9,20],
[15,7]
]

題解

1)使用一個(gè)Queue保存TreeNode 2)記錄當(dāng)前行size,遍歷size次數(shù),直到取出當(dāng)前行所有值。這道題,比103行要簡(jiǎn)單點(diǎn),不需要記錄每行的方向。

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> ress = new ArrayList<>();
        if (root == null) {
            return ress;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        TreeNode curNode = root;
        while (!queue.isEmpty()) {
            int size = queue.size();
            LinkedList<Integer> res = new LinkedList<>();
            while (size -- > 0) {
                curNode = queue.poll();
                if (curNode.left != null) {
                    queue.offer(curNode.left);
                }
                if (curNode.right != null) {
                    queue.offer(curNode.right);
                }
                res.offerLast(curNode.val);
            }
            ress.add(res);
        }
        return ress;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容