LeetCode题库解答与分析——#103. 二叉树的锯齿形层次遍历BinaryTreeZigzagLevelOrderTraversal

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

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

    3
   / \
  9  20
    /  \
   15   7

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

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

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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

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

个人思路:

二叉树的层次遍历的思路为基础,定义direction作为存储方向(true代表向右存储,false代表向左存储),以满足锯齿形存储的要求,仍然按层次遍历取得子数组,每次内循环获得一层的元素,并在每一轮结束后根据direction的布尔值进行顺序存储或反向存储,构成新的子数组加入总数组,最终得到锯齿形层次遍历数组。

代码(Java):

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        Queue<TreeNode> queue=new LinkedList<TreeNode>();
        List<List<Integer>> visited=new LinkedList<List<Integer>>();
        int row=0,col=0;
        Boolean direction=true;//true代表向右,false代表向左
        if(root!=null){queue.offer(root);}
        else{return visited;}
        while(!queue.isEmpty()){
            int level=queue.size();
            List<Integer> sub_visited=new LinkedList<Integer>();
            Stack<Integer> sub_stack=new Stack<Integer>();
            List<Integer> sub_queue=new LinkedList<Integer>();
            for(int i=0;i<level;i++){              
                if(queue.peek().left!=null){queue.offer(queue.peek().left);} 
                if(queue.peek().right!=null){queue.offer(queue.peek().right);} 
                int value=queue.poll().val;
                sub_stack.push(value); 
                sub_queue.add(value);
            }
            if(direction==true){
                sub_visited=sub_queue;
            }
            else{
                while(!sub_stack.isEmpty()){
                    sub_visited.add(sub_stack.pop());
                }                
            }
            direction=!direction;
            visited.add(sub_visited);
        }
        return visited;
    }
}


猜你喜欢

转载自blog.csdn.net/weixin_38385524/article/details/79875630