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

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

Open
HealUP opened this issue May 18, 2023 · 0 comments
Open

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

HealUP opened this issue May 18, 2023 · 0 comments
Labels
算法 记录刷题记录,代码随想录

Comments

@HealUP
Copy link
Owner

HealUP commented May 18, 2023

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

思路:

  • 层序遍历 一个while 一个for循环
  • 处理for循环的时候,让下标i小于数组最大下标的每一层的每一个节点指向下一个节点的值(只是查看值,而不弹出,用peek())
/*
// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}
    
    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return root;
        }
        Queue<Node> que = new LinkedList<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int len = que.size();//每一层的数量是会改变的,记录下来
            for (int i = 0; i < len; i++) {
                Node node = que.poll();
                //连接每一层的节点,当该层的节点的数量大于1就可连接
                if (i < len - 1) {
                    node.next = que.peek();//不弹出该节点,只是查看
                }
                //扩展下一层的节点放入队列中
                if (node.left != null) que.offer(node.left);
                if (node.right != null) que.offer(node.right);
            } 
        }
        return root;
    }
}
@HealUP HealUP added 算法 记录刷题记录,代码随想录 二叉树 labels May 18, 2023
@HealUP HealUP removed the 二叉树 label Jul 29, 2023
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