Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

填充同一层的兄弟节点 #91

Open
louzhedong opened this issue Nov 22, 2018 · 0 comments
Open

填充同一层的兄弟节点 #91

louzhedong opened this issue Nov 22, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

习题

出处 LeetCode 算法第116题

给定一个二叉树

struct TreeLinkNode {
  TreeLinkNode *left;
  TreeLinkNode *right;
  TreeLinkNode *next;
}

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL

初始状态下,所有 next 指针都被设置为 NULL

说明:

  • 你只能使用额外常数空间。
  • 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
  • 你可以假设它是一个完美二叉树(即所有叶子节点都在同一层,每个父节点都有两个子节点)。

示例:

给定完美二叉树,

     1
   /  \
  2    3
 / \  / \
4  5  6  7

调用你的函数后,该完美二叉树变为:

     1 -> NULL
   /  \
  2 -> 3 -> NULL
 / \  / \
4->5->6->7 -> NULL

思路

采用遍历的方式

解答

var connect = function (root) {
  if (root == null) {
    root = {};
    return;
  }
  for (var item = root; item.left != null; item = item.left) {
    for (var cursor = item; cursor != null; cursor = cursor.next) {
      cursor.left.next = cursor.right;
      if (cursor.next != null) {
        cursor.right.next = cursor.next.left;
      }
    }
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant