将二叉树变为链表
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
思路:前序遍历树,将节点存储进来,遍历后连接各个节点。
public void flatten(TreeNode root) {
Deque<TreeNode> deque = new ArrayDeque<TreeNode>();
if(root != null) deque.add(root);
TreeNode cur = null, tmp = null;
while(!deque.isEmpty()){
tmp = deque.pollLast();
if(tmp.right != null) deque.add(tmp.right);
if(tmp.left != null) deque.add(tmp.left);
if(tmp != root){
cur.right = tmp;
cur.left = null;//不置为null会有问题。
}
cur = tmp;
}
if(tmp != null) tmp.right = null;
}
将二叉树同层节点相连
struct TreeLinkNode {
TreeLinkNode left;
TreeLinkNode right;
TreeLinkNode next;
}
1.满二叉树
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
思路:递归做,如果是满二叉树,直接递归一层一层让左孩子连
public void connect(TreeLinkNode root) {
TreeLinkNode start = root;
while(start != null && start.left != null){
TreeLinkNode p = start, q = new TreeLinkNode(0);
while(p != null){
q.next = p.left;
p.left.next = p.right;
q = p.right;
p = p.next;
}
start = start.left;
}
}
2.普通二叉树
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 ->3 -> NULL
/ \ \
4-> 5-> 7 -> NULL
public void connectII(TreeLinkNode root) {
TreeLinkNode start = root;
while(start != null){
TreeLinkNode p = start, sonstart = new TreeLinkNode(0), q = sonstart;
while(p != null){
if(p.left != null){
q.next = p.left;
q = p.left;
}
if(p.right != null){
q.next = p.right;
q = p.right;
}
p = p.next;
}
start = sonstart.next;
}
}