题目:
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1 / 2 3 / \ / 4 5 6 7
After calling your function, the tree should look like:
1 -> NULL / 2 -> 3 -> NULL / \ / 4->5->6->7 -> NULL
思路1:使用深度优先搜索遍历
代码:
public static void connect_DFS(TreeLinkNode root) { if(root != null){ if(root.left != null && root.right != null){ root.left.next = root.right; System.out.println(root.left.val +" Next : "+ root.right.val); if(root.left.right != null && root.right.left != null){ root.left.right.next = root.right.left; System.out.println(root.left.right.val +" Next : "+ root.right.left.val); } } if(root.left != null ){ connect_DFS(root.left); } if(root.right != null ){ connect_DFS(root.right); } } }
分析:存在缺点:第一左子树的最右边的节点的情况处理不到,分析貌似用深搜不行
时间: 2024-10-28 23:09:30