117. Populating Next Right Pointers in Each Node II
2016-09-30 15:35
441 查看
解题思路:
和Populating Next Right Pointers in Each Node(https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)一样采用dfs,但是注意在dfs的时候需要多做一些next节点是否存在的判断。并且需要注意的是,DFS时要先遍历right son, 再遍历left son。
如下例:
2
1 3
0 7 9 1
1 1 0 8 8
若先搜索left son,再搜索right son,在遍历到值为7的节点,9->1的next连接还没有建立。
代码如下:
和Populating Next Right Pointers in Each Node(https://leetcode.com/problems/populating-next-right-pointers-in-each-node/)一样采用dfs,但是注意在dfs的时候需要多做一些next节点是否存在的判断。并且需要注意的是,DFS时要先遍历right son, 再遍历left son。
如下例:
2
1 3
0 7 9 1
1 1 0 8 8
若先搜索left son,再搜索right son,在遍历到值为7的节点,9->1的next连接还没有建立。
代码如下:
public class Solution { //most right son in the next generation public TreeLinkNode mostRightSon(TreeLinkNode root){ if (root == null) return null; else return (root.right == null) ? root.left : root.right; } //most left son of root.next(or root.next.next...) in the next generation public TreeLinkNode mostLeftSon(TreeLinkNode root){ TreeLinkNode node = root; while(node != null){ if (node.left != null) return node.left; else if (node.right != null) return node.right; else node = node.next; } return null; } public void connect(TreeLinkNode root) { if (root == null) return; if (root.left != null && root.right != null){ root.left.next = root.right; } TreeLinkNode mostRightSon = mostRightSon(root); if (mostRightSon != null){ mostRightSon.next = mostLeftSon(root.next); } //root.right must be processed before left, because this is a depth first search so that the next of your right cousin may not have been processed. connect(root.right); connect(root.left); } }
相关文章推荐
- Java for LeetCode 117 Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- LeetCode(117) Populating Next Right Pointers in Each Node II
- (M)DFS:117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II Leetcode Python
- [LeetCode#117]Populating Next Right Pointers in Each Node II
- leetcode_question_117 Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- [LeetCode 116 117] - 填充每一个节点的指向右边邻居的指针I & II (Populating Next Right Pointers in Each Node I & II)
- LeetCode 117 Populating Next Right Pointers in Each Node II
- leetcode117~Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 【LeetCode-面试算法经典-Java实现】【117-Populating Next Right Pointers in Each Node(二叉树链接右指针II)】
- 117. Populating Next Right Pointers in Each Node II
- LeetCode.116(117) Populating Next Right Pointers in Each Node && II
- Leetcode 117 Populating Next Right Pointers in Each Node II
- [LeetCode 117] Populating Next Right Pointers in Each Node II
- Leetcode 笔记 117 - Populating Next Right Pointers in Each Node II
- [LeetCode]题解(python):117-Populating Next Right Pointers in Each Node II