Problem
Given a binary tree, return the zigzag level order traversal of its nodes" values. (ie, from left to right, then right to left for the next level and alternate between).
ExampleGiven binary tree {3,9,20,#,#,15,7},
3 / 9 20 / 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]Note Solution
public class Solution { public ArrayList> zigzagLevelOrder(TreeNode root) { ArrayList > res = new ArrayList(); if (root == null) return res; boolean LR = true; Stack stack = new Stack(); stack.push(root); while (!stack.isEmpty()) { Stack curStack = new Stack(); ArrayList curList = new ArrayList(); while (!stack.isEmpty()) { TreeNode cur = stack.pop(); curList.add(cur.val); if (LR) { if (cur.left != null) curStack.push(cur.left); if (cur.right != null) curStack.push(cur.right); } else { if (cur.right != null) curStack.push(cur.right); if (cur.left != null) curStack.push(cur.left); } } stack = curStack; res.add(curList); LR = !LR; } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65928.html
Problem Given a binary tree, return the level order traversal of its nodes values. (ie, from left to right, level by level). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / 9 20 / ...
摘要:棧迭代復(fù)雜度時(shí)間空間遞歸??臻g對于二叉樹思路用迭代法做深度優(yōu)先搜索的技巧就是使用一個(gè)顯式聲明的存儲遍歷到節(jié)點(diǎn),替代遞歸中的進(jìn)程棧,實(shí)際上空間復(fù)雜度還是一樣的。對于先序遍歷,我們出棧頂節(jié)點(diǎn),記錄它的值,然后將它的左右子節(jié)點(diǎn)入棧,以此類推。 Binary Tree Preorder Traversal Given a binary tree, return the preorder tr...
摘要:根據(jù)二叉平衡樹的定義,我們先寫一個(gè)求二叉樹最大深度的函數(shù)。在主函數(shù)中,利用比較左右子樹的差值來判斷當(dāng)前結(jié)點(diǎn)的平衡性,如果不滿足則返回。 Problem Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as...
Problem Binary Tree PruningWe are given the head node root of a binary tree, where additionally every nodes value is either a 0 or a 1. Return the same tree where every subtree (of the given tree) not...
摘要:做了幾道二分法的題目練手,發(fā)現(xiàn)這道題已經(jīng)淡忘了,記錄一下。這道題目的要點(diǎn)在于找的區(qū)間。邊界條件需要注意若或數(shù)組為空,返回空當(dāng)前進(jìn)到超出末位,或超過,返回空每次創(chuàng)建完根節(jié)點(diǎn)之后,要將加,才能進(jìn)行遞歸。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...
閱讀 3815·2021-11-22 13:52
閱讀 3662·2019-12-27 12:20
閱讀 2421·2019-08-30 15:55
閱讀 2202·2019-08-30 15:44
閱讀 2292·2019-08-30 13:16
閱讀 611·2019-08-28 18:19
閱讀 1924·2019-08-26 11:58
閱讀 3471·2019-08-26 11:47