您的位置:首页 > 其它

【LeetCode】103. Binary Tree Zigzag Level Order Traversal(Medium)解题报告

2018-03-14 18:28 489 查看
【LeetCode】103. Binary Tree Zigzag Level Order Traversal(Medium)解题报告

题目地址:https://leetcode.com/problems/binary-tree-level-order-traversal/description/

题目描述:

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


Solution:

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
二叉树的层序遍历,很经常出现的一个问题
第一种方法:queue
time : O(n)
space : O(n)
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i=0 ; i<size ;i++){
TreeNode cur = queue.poll();
if(cur.left!=null) queue.offer(cur.left);
if(cur.right!=null) queue.offer(cur.right);
list.add(cur.val);
}
res.add(list);
}
return res;
}
}/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
也可以用前序转层序做
time : O(n)
space : O(n)
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return res;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean x = true;
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
for(int i=0 ; i<size ; i++){
TreeNode cur = queue.poll();
if(x){
list.add(cur.val);
}else{
list.add(0,cur.val);
}
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
}
res.add(list);
x = x ? false : true;
}
return res;
}
}


Date:2018年3月14日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息