• Binary Tree Zigzag Level Order Traversal 解答


    Question

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

    For 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]
    ]

    Solution

    Traditional way is to use two queues to implement level order traversal. Here, we just add a flag to indicate whether it's from left to right or from right to left.

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
    12         List<List<Integer>> result = new ArrayList<List<Integer>>();
    13         if (root == null)
    14             return result;
    15         // Set a flag to help judge traversal sequence
    16         // flag = 0, from left to right; flag = 1, from right to left
    17         int flag = 0;
    18         List<TreeNode> current = new ArrayList<TreeNode>();
    19         List<TreeNode> next;
    20         current.add(root);
    21         
    22         while (current.size() > 0) {
    23             List<Integer> oneRecord = new ArrayList<Integer>();
    24             next = new ArrayList<TreeNode>();
    25             for (TreeNode tmpNode : current) {
    26                 if (tmpNode.left != null)
    27                     next.add(tmpNode.left);
    28                 if (tmpNode.right != null)
    29                     next.add(tmpNode.right);
    30                 if (flag == 0)
    31                     oneRecord.add(tmpNode.val);
    32                 else
    33                     oneRecord.add(0, tmpNode.val);
    34             }
    35             result.add(oneRecord);
    36             current = next;
    37             flag = 1 - flag;
    38         }
    39         return result;
    40     }
    41 }
  • 相关阅读:
    求解未知矩阵的一些方法
    数二2019-19真题最简单的解法
    极坐标转化为参数方程的题目
    隐函数的不定积分
    Go 语言高性能编程
    1457. Pseudo-Palindromic Paths in a Binary Tree (M)
    0754. Reach a Number (M)
    1345. Jump Game IV (H)
    0091. Decode Ways (M)
    0498. Diagonal Traverse (M)
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4834105.html
Copyright © 2020-2023  润新知