您的位置:首页 > Web前端 > Node.js

LeetCode 117 Populating Next Right Pointers in Each Node II

2017-08-31 15:08 369 查看
/**
* 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 mostLeft = root;

while (mostLeft != null) {
root = mostLeft;
while(root != null) {
if (root.left != null && root.right != null) {
root.left.next = root.right;
root.right.next = getNextNode(root.next);
} else if (root.left != null || root.right != null) {
getNextNode(root).next = getNextNode(root.next);
}
root = root.next;
}
mostLeft = getNextNode(mostLeft);
}
}

private TreeLinkNode getNextNode(TreeLinkNode root) {
if (root == null) {
return null;
}
if (root.left != null) {
return root.left;
}

if (root.right != null) {
return root.right;
}

return getNextNode(root.next);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: