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

116. 填充每个节点的下一个右侧节点指针 #63

Open
yankewei opened this issue Oct 15, 2020 · 1 comment
Open

116. 填充每个节点的下一个右侧节点指针 #63

yankewei opened this issue Oct 15, 2020 · 1 comment
Labels
中等 题目难度为中等 题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法

Comments

@yankewei
Copy link
Owner

给定一个完美二叉树,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

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

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

示例:

示例

输入:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":null,"right":null,"val":4},"next":null,"right":{"$id":"4","left":null,"next":null,"right":null,"val":5},"val":2},"next":null,"right":{"$id":"5","left":{"$id":"6","left":null,"next":null,"right":null,"val":6},"next":null,"right":{"$id":"7","left":null,"next":null,"right":null,"val":7},"val":3},"val":1}

输出:{"$id":"1","left":{"$id":"2","left":{"$id":"3","left":null,"next":{"$id":"4","left":null,"next":{"$id":"5","left":null,"next":{"$id":"6","left":null,"next":null,"right":null,"val":7},"right":null,"val":6},"right":null,"val":5},"right":null,"val":4},"next":{"$id":"7","left":{"$ref":"5"},"next":null,"right":{"$ref":"6"},"val":3},"right":{"$ref":"4"},"val":2},"next":null,"right":{"$ref":"7"},"val":1}
解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。

提示:

  • 你只能使用常量级额外空间。
  • 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node

@yankewei yankewei added 中等 题目难度为中等 题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 labels Oct 15, 2020
@yankewei
Copy link
Owner Author

其实这个题的意思就是,在每一层节点,如果这一个节点的右侧还有节点,那么next节点指向它即可。

层次遍历

层次遍历最容易的,因为正好可以一层一层的遍历节点。
Leetcode题解-2

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Left *Node
 *     Right *Node
 *     Next *Node
 * }
 */

func connect(root *Node) *Node {
    if root == nil {
	return nil
    }
    var queue []*Node
    queue = append(queue, root)
    for len(queue) != 0 {
	tQueue := queue
	queue = []*Node{}
	for i := 0; i < len(tQueue); i++ {
	    if tQueue[i].Left != nil && tQueue[i].Right != nil {
		queue = append(queue, tQueue[i].Left, tQueue[i].Right)
	    }
            // 如果这是这一层的最后一个节点,next指针指向nil即可,否则就指向下一个节点
	    if i != len(tQueue)-1 {
		tQueue[i].Next = tQueue[i+1]
	    }
	}
    }
    return root
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 题目难度为中等 题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法
Projects
None yet
Development

No branches or pull requests

1 participant