本文主要是介绍leetcode----116. Populating Next Right Pointers in Each Node,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
链接:
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
大意:
给定一棵完全二叉树root,该二叉树的所有叶子节点都在同一层。该二叉树数据结构定义如下:
class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val,Node _left,Node _right,Node _next) {val = _val;left = _left;right = _right;next = _next;}
};
left和right域的解释与普通二叉树一样。而每个节点的next域指向同一层下一个位于它右边的节点,如果右边没有节点,则指向空,现在需要补全每个节点的next域指向信息。例子:
注意:上述说明中的$id为节点的编号,val才是节点的值
思路:
使用二叉树层次遍历的递归解法。
关于二叉树的层次遍历解法还可以看另一题:使用递归法解决按Z字形打印二叉树节点
代码:
/*
// Definition for a Node.
class Node {public int val;public Node left;public Node right;public Node next;public Node() {}public Node(int _val,Node _left,Node _right,Node _next) {val = _val;left = _left;right = _right;next = _next;}
};
/*
// $id是节点的编号 val才是节点的值
{"$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}
*/
// 可用层次遍历的递归法解决
class Solution {public Node connect(Node root) {connect(root, 0, new ArrayList<>());return root;}public void connect(Node root, int h, List<List<Node>> list) {if (root == null)return ;if (h == list.size())list.add(new ArrayList<>());if (list.get(h).size() > 0) {list.get(h).get(list.get(h).size() - 1).next = root;}list.get(h).add(root);connect(root.left, h + 1, list);connect(root.right, h + 1, list);}
}
结果:
结论:
理清思路,想好方法,动手写代码。
这篇关于leetcode----116. Populating Next Right Pointers in Each Node的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!