劍指offer最優(yōu)解Java版-按之字形順序打印二叉樹(shù)

劍指offer專題地址

劍指offer索引地址

題目描述

請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù)按照之字形打印二叉樹(shù),即第一行按照從左到右的順序打印,第二層按照從右至左的順序打印,第三行按照從左到右的順序打印,其他行以此類推。

解決方法

在層序遍歷的基礎(chǔ)上,增加根據(jù)行數(shù)進(jìn)行正向反向迭代(正向反向迭代利用LinkedList雙向鏈表)

class TreeNode {
    int      val   = 0;
    TreeNode left  = null;
    TreeNode right = null;

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

public class Solution {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> layers = new ArrayList<>();
        if (pRoot == null)
            return layers;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        int depth = 0;
        while (!queue.isEmpty()) {
            depth++;
            ArrayList<Integer> layer = new ArrayList<>();
            int cur = 0, size = queue.size();
            if ((depth & 1) == 0) { //如果是偶數(shù)層倒序添加
                Iterator<TreeNode> it = queue.descendingIterator();
                while (it.hasNext()) {
                    layer.add(it.next().val);
                }
            } else { //如果是奇數(shù)層正序添加
                Iterator<TreeNode> it = queue.iterator();
                while (it.hasNext()) {
                    layer.add(it.next().val);
                }
            }
            while (cur < size) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                cur++;
            }
            layers.add(layer);
        }
        return layers;
    }
}

復(fù)雜度分析:

  • 時(shí)間復(fù)雜度:O(n)。
  • 空間復(fù)雜度:O(n)。
哎呀,如果我的名片丟了。微信搜索“全菜工程師小輝”,依然可以找到我
最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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