提交 f7fb3a41 编写于 作者: L liu13

20190129

上级 6fe551fc
package code;
/*
* 103. Binary Tree Zigzag Level Order Traversal
* 题意:蛇形层次遍历
* 难度:Medium
* 分类:Stack, Tree, Breadth-first Search
* 思路:层次遍历,加了个flag每次是在list头添加或尾添加
* Tips:Bingo!
*/
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class lc103 {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root==null) return res;
Queue<TreeNode> q = new ArrayDeque();
q.add(root);
boolean flag = true;
while(!q.isEmpty()){
int size = q.size();
List<Integer> ls = new ArrayList<>();
while(size>0){
TreeNode temp = q.remove();
if(flag) ls.add(temp.val);
else ls.add(0,temp.val); //在头部添加
if(temp.left!=null) q.add(temp.left);
if(temp.right!=null) q.add(temp.right);
size--;
}
res.add(ls);
flag = !flag;
}
return res;
}
}
package code;
/*
* 116. Populating Next Right Pointers in Each Node
* 题意:设置二叉树的next指针,指向同层右侧节点
* 难度:Medium
* 分类:Tree, Depth-first Search
* 思路:自己写的递归,中间有冗余。迭代方法和较优的递归会利用先前已经设置的next指针,做下一步操作
* Tips:复习时多看一下,自己没想起来利用已经设置好的指针
*/
public class lc116 {
public class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
}
public void connect(TreeLinkNode root) {
if(root==null) return;
helper(root.left, root.right);
}
public void helper(TreeLinkNode root1, TreeLinkNode root2){//较慢,也能过
if( root1==null || root2==null ) return;
root1.next = root2;
helper(root1.left, root1.right);
helper(root1.right, root2.left); //会重复设置
helper(root2.left,root2.right);
}
public void connect2(TreeLinkNode root) {
while(root!=null){
TreeLinkNode start = root;
while(start!=null){
if(start.left!=null){
start.left.next = start.right; //设置下一层的next指针
if(start.next!=null){
start.right.next = start.next.left;
}
}
start = start.next;
}
root = root.left;
}
}
}
package code;
import java.util.List;
public class lc118 {
public List<List<Integer>> generate(int numRows) {
while(numRows>0){
}
}
}
......@@ -69,6 +69,7 @@ Language: Java
| 084 [Java](./code/lc84.java)
| 085 [Java](./code/lc85.java)
| 088 [Java](./code/lc88.java)
| 091 [Java](./code/lc91.java)
| 094 [Java](./code/lc94.java)
| 096 [Java](./code/lc96.java)
| 098 [Java](./code/lc98.java)
......@@ -76,6 +77,7 @@ Language: Java
| 102 [Java](./code/lc102.java)
| 104 [Java](./code/lc104.java)
| 105 [Java](./code/lc105.java)
| 108 [Java](./code/lc108.java)
| 114 [Java](./code/lc114.java)
| 121 [Java](./code/lc121.java)
| 122 [Java](./code/lc122.java)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册