LeetCode#103 二叉树的锯齿形层次遍历 Java

@author: sdubrz
@date: 2020.04.20
题号: 103
题目难度: 中等
考察内容: 栈,树
原题链接 https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
题目的著作权归领扣网络所有,商业转载请联系官方授权,非商业转载请注明出处。
解题代码转载请联系 lwyz521604#163.com

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

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

通过次数43,767 提交次数80,696

解法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 import java.util.*;
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> list = new LinkedList<>();
        if(root==null){
            return list;
        }
        Stack<TreeNode> stack1 = new Stack<>();
        stack1.push(root);

        boolean postive = true;

        while(!stack1.isEmpty()){
            Stack<TreeNode> stack2 = new Stack<>();
            List<Integer> subList = new LinkedList<>();
            while(!stack1.isEmpty()){
                TreeNode current = stack1.pop();
                subList.add(current.val);
                if(postive){
                    if(current.left!=null){
                        stack2.push(current.left);
                    }
                    if(current.right!=null){
                        stack2.push(current.right);
                    }
                }else{
                    if(current.right!=null){
                        stack2.push(current.right);
                    }
                    if(current.left!=null){
                        stack2.push(current.left);
                    }
                }
                
            }
            postive = !postive;
            // while(!stack2.isEmpty()){
            //     stack1.push(stack2.pop());
            // }
            stack1 = stack2;
            list.add(subList);
        }

        return list;

    }
}

在 LeetCode 系统中的提交结果:

执行结果: 通过 显示详情
执行用时 : 2 ms, 在所有 Java 提交中击败了 26.86% 的用户
内存消耗 : 39.8 MB, 在所有 Java 提交中击败了 7.41% 的用户
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章