【LeetCode】Populating Next Right Pointers in Each Node
编程小记,已供重温!!
Populating Next Right Pointers in Each Node
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4-> 5->6 -> 7 -> NULL
先不管空间复杂度,最直接想到的方法解决。
此题,我的第一反映是广度优先遍历。按层访问。每一层自左向右按顺序链接!需要借助于队列来实现。(其实这种方式还适合解决不是perfect binary tree的题目,^_^,Populating Next Right Pointers in Each Node II就是这样的问题。 )这种实现方法的空间复杂度是o(n)
思路一的实现方式:
public static void connect(TreeLinkNode root) { if (root == null) { return; } int count=0; Queue<TreeLinkNode>queue=new LinkedList<TreeLinkNode>(); queue.add(root); count=queue.size(); while(!queue.isEmpty()){ TreeLinkNode top=queue.poll(); count--; if(top.left!=null){ queue.add(top.left); } if(top.right!=null){ queue.add(top.right); } if(count==0){ top.next=null; count=queue.size(); } else{ top.next=queue.peek(); } } }
思路二是,我们仔细观察发现,链接分为2种情况:情况1是链接root节点的左子树与右子树。情况2是链接节点2的右子树与节点3的左子树。
1 2 ——》 3 / \ / \ / \ 2 -> 3 4 5 ——》 6 7
(1) (2)
剩余的就是选择一个普通的遍历方式。空间复杂度是O(log n)
思路二实现方式
public static void tra(TreeLinkNode root) { if (root == null) { return; } Stack<TreeLinkNode> stack = new Stack<>(); while (null != root || !stack.isEmpty()) { while (null != root) { stack.push(root);
//visit
System.out.println(root.val);
// root = root.left; } root = stack.pop(); root = root.right; } }
遍历的同时,链接2种。
public static void connect(TreeLinkNode root) { if (root == null) { return; } Stack<TreeLinkNode> stack = new Stack<>(); while (null != root || !stack.isEmpty()) { while (null != root) { stack.push(root); if (root.left != null) { root.left.next = root.right; if (root.next != null) { root.right.next = root.next.left; } } root = root.left; } root = stack.pop(); root = root.right; } }
考虑时间复杂度:
经过分析我们发现,只要是能够保证找到下一行的第一个节点以及当前行的下一个节点就可以了,所以,可以采用如下的方式实现:
思路3实现方法
public static void connect3(TreeLinkNode root) { if (root == null) { return; } TreeLinkNode nextLinkNode=null; while (null!=root) { nextLinkNode=root; while (nextLinkNode!=null) { if (nextLinkNode.left != null) { nextLinkNode.left.next = nextLinkNode.right; if (nextLinkNode.next != null) { nextLinkNode.right.next = nextLinkNode.next.left; } } nextLinkNode = nextLinkNode.left; } root = root.left; } }
空间复杂度为O(1)。