国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Binary Tree Zigzag Level Orde

AlphaGooo / 2703人閱讀

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).

Example

Given 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;
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65928.html

相關文章

  • [LintCode/LeetCode] Binary Tree Level Order Traver

    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 / ...

    makeFoxPlay 評論0 收藏0
  • [Leetcode] Binary Tree Traversal 二叉樹遍歷

    摘要:棧迭代復雜度時間空間遞歸棧空間對于二叉樹思路用迭代法做深度優先搜索的技巧就是使用一個顯式聲明的存儲遍歷到節點,替代遞歸中的進程棧,實際上空間復雜度還是一樣的。對于先序遍歷,我們出棧頂節點,記錄它的值,然后將它的左右子節點入棧,以此類推。 Binary Tree Preorder Traversal Given a binary tree, return the preorder tr...

    RaoMeng 評論0 收藏0
  • [LintCode/LeetCode] Balanced Binary Tree

    摘要:根據二叉平衡樹的定義,我們先寫一個求二叉樹最大深度的函數。在主函數中,利用比較左右子樹的差值來判斷當前結點的平衡性,如果不滿足則返回。 Problem Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as...

    morgan 評論0 收藏0
  • [LintCode/LeetCode] Binary Tree Pruning

    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...

    rockswang 評論0 收藏0
  • [LintCode/LeetCode] Construct Binary Tree from Tr

    摘要:做了幾道二分法的題目練手,發現這道題已經淡忘了,記錄一下。這道題目的要點在于找的區間。邊界條件需要注意若或數組為空,返回空當前進到超出末位,或超過,返回空每次創建完根節點之后,要將加,才能進行遞歸。 Construct Binary Tree from Inorder and Preorder Traversal Problem Given preorder and inorder t...

    馬忠志 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<