首页 > 代码库 > [Leetcode] Populating Next Right Pointers in Each Node II
[Leetcode] Populating Next Right Pointers in Each Node II
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
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
Solution:
http://blog.csdn.net/wzy_1988/article/details/17412025
这道题目首要是找到右孩子的第一个有效的next链接节点,然后再处理左孩子。然后依次递归处理右孩子,左孩子
1 /** 2 * Definition for binary tree with next pointer. 3 * public class TreeLinkNode { 4 * int val; 5 * TreeLinkNode left, right, next; 6 * TreeLinkNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution {10 public void connect(TreeLinkNode root) {11 if (root == null)12 return;13 TreeLinkNode p = root.next;14 while (p != null) {15 if(p.left!=null){16 p=p.left;17 break;18 }19 if(p.right!=null){20 p=p=p.right;21 break;22 }23 p=p.next;24 }25 if (root.right != null) {26 root.right.next = p;27 }28 if (root.left != null) {29 root.left.next = (root.right == null) ? p : root.right;30 }31 connect(root.right);32 connect(root.left);33 }34 }
[Leetcode] Populating Next Right Pointers in Each Node II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。