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

5.1.12 Populating Next Right Pointers in Each Node II

2014-07-16 03:37 211 查看
原题链接:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/

假设原始的树如下:



方法I: 递归 Time O(n), Space O(1) ( 递归要用到栈,所以是O(1)吗?)

public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
if(root.left != null){
root.left.next = root.right == null ? getNext(root) : root.right;
}
if(root.right != null){
root.right.next = getNext(root);
}
connect(root.right);
connect(root.left);
}

private TreeLinkNode getNext(TreeLinkNode n){
TreeLinkNode cur = n;
while(cur.next != null){
cur = cur.next;
if(cur.left != null){
return cur.left;
}
if(cur.right != null){
return cur.right;
}
}
return null;
}
}
















方法II: 迭代 (见leetcode上戴的代码。没看懂。)

另:http://n00tc0d3r.blogspot.com/2013/05/populating-next-right-pointers-for-each.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: