[LeetCode] Populating Next Right Pointers in Each Node II

来源:互联网 发布:php 微信app支付demo 编辑:程序博客网 时间:2024/06/18 18:04

Total Accepted: 8762 Total Submissions: 29878

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
         1 -> NULL       /  \      2 -> 3 -> NULL     / \   / \    4->5 ->6->7 -> NULL
<-------------------------
 
/** * 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 || (root.left == null && root.right == null)) return;                if (root.left != null ) {            if (root.right != null) root.left.next = root.right;            else                    root.left.next = getChildNodeFromNext(root);        }                if (root.right != null ) root.right.next = getChildNodeFromNext(root);        if (root.right  != null) connect(root.right);        if (root.left   != null) connect(root.left);    }        // find the first child node in root.next.next...    public TreeLinkNode getChildNodeFromNext(TreeLinkNode root) {        TreeLinkNode node = root.next;        while (node != null) {            if (node.left != null)  return node.left;                   if (node.right != null) return node.right;                  node = node.next;        }                return null;    }}

0 0
原创粉丝点击