美文网首页
LintCode - 二叉树的锯齿形层次遍历(中等)

LintCode - 二叉树的锯齿形层次遍历(中等)

作者: 柒黍 | 来源:发表于2017-09-23 00:59 被阅读0次

版权声明:本文为博主原创文章,未经博主允许不得转载。

难度:中等
要求:

给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)

样例:
给出一棵二叉树 {3,9,20,#,#,15,7},
    3
   / \
  9  20
    /  \
   15   7

返回其锯齿形的层次遍历为:
[
  [3],
  [20,9],
  [15,7]
]
实现:
/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /*
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {

        List<List<Integer>> ret = new ArrayList<List<Integer>>();
        if (root == null) {
            return ret;
        }

        List<Integer> cell = new ArrayList();
        TreeNode last = root;
        TreeNode nLast = root;

        LinkedList<TreeNode> queue = new LinkedList();
        queue.add(root);

        //标记锯齿方向
        boolean flag = true;

        while (!queue.isEmpty()) {
            TreeNode node = queue.pop();
            if (flag) {
                cell.add(node.val);
            } else {
                cell.add(0, node.val);
            }

            if (node.left != null) {
                queue.add(node.left);
                nLast = node.left;
            }

            if (node.right != null) {
                queue.add(node.right);
                nLast = node.right;
            }

            //换行
            if (node == last) {
                last = nLast;
                ret.add(cell);
                cell = new ArrayList();
                flag = !flag;
            }
        }
        return ret;
    }
}

相关文章

网友评论

      本文标题:LintCode - 二叉树的锯齿形层次遍历(中等)

      本文链接:https://www.haomeiwen.com/subject/czmqextx.html