LeetCode Populating Next Right Pointers in Each Node II
来源:互联网 发布:乐安全软件 编辑:程序博客网 时间:2024/04/29 02:59
原题链接在这里:https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
本题是Populating Next Right Pointers in Each Node的进阶版。关键是在有null的时候如何找到下一节点,通过while loop找到next节点,while loop 很关键。
Note:1. 递归时先递归右子树,后递归左子树,否则会出错。
2. while loop中要加break, 否则会infinite loop.
AC Java:
/** * Definition for binary tree with next pointer. * public class TreeLinkNode { * int val; * TreeLinkNode left, right, next; * TreeLinkNode(int x) { val = x; } * } */public class Solution { public void connect(TreeLinkNode root) { if(root == null){ return; } TreeLinkNode next = null; TreeLinkNode rootNext = root.next; while(rootNext != null){ if(rootNext.left != null){ next = rootNext.left; break; }else if(rootNext.right != null){ next = rootNext.right; break; }else{ rootNext = rootNext.next; } } if(root.right != null){ root.right.next = next; } if(root.left != null){ if(root.right != null){ root.left.next = root.right; }else{ root.left.next = next; } } connect(root.right); connect(root.left); }}
0 0
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- LeetCode Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- leetcode 79: Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node ii
- leetcode Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node II
- [Leetcode]Populating Next Right Pointers in Each Node II
- [leetcode] Populating Next Right Pointers in Each Node II
- LeetCode-Populating Next Right Pointers in Each Node II
- LeetCode - Populating Next Right Pointers in Each Node II
- [LeetCode]Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node II
- LeetCode | Populating Next Right Pointers in Each Node II
- [leetcode]Populating Next Right Pointers in Each Node II
- 【LeetCode OJ】Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- UVA1608_Non-boring sequences
- UVA1442_Cave
- spring mvc的图片上传与显示
- HDU3951_Coin Game
- Gif 在线制作
- LeetCode Populating Next Right Pointers in Each Node II
- magento 中文店铺设置
- Item 24:用非成员函数来支持所有元的类型转换 Effective C++笔记
- Spring管理filter和servlet
- leetcode 279: Perfect Squares
- ACM-括号匹配问题
- 9.8学习总结
- 9.9学习总结
- 【小熊刷题】Binary Search Tree Iteration <Leetcode 179, Java>