
class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
}
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null) return;
while(root!=null){
TreeLinkNode tempLevelFirst=new TreeLinkNode(0);
TreeLinkNode cur=tempLevelFirst;
while(root!=null){
if(root.left!=null){
cur.next=root.left;
cur=cur.next;
}
if(root.right!=null){
cur.next=root.right;
cur=cur.next;
}
root=root.next;
}
root=tempLevelFirst.next;
}
}
//二叉树的遍历
public void preOrder(TreeLinkNode root){
if(root!=null){
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
}
public static void main(String[]args){
//System.out.println("Hello World!");
/**
1
2 3
4 5 7
*/
TreeLinkNode root=new TreeLinkNode(1);
root.left=new TreeLinkNode(2);
root.right=new TreeLinkNode(3);
root.left.left=new TreeLinkNode(4);
root.left.right=new TreeLinkNode(5);
root.right.right=new TreeLinkNode(7);
Solution s=new Solution();
s.preOrder(root);
}
}
本文介绍了一种特殊的二叉树节点结构TreeLinkNode,并通过一个解决方案类实现了将二叉树中同一层级的节点进行链接的功能。具体实现是通过一次遍历完成节点之间的连接,而非传统的递归遍历。此外,还提供了二叉树的前序遍历方法以展示树的结构。
1130

被折叠的 条评论
为什么被折叠?



