标签:
题目:
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:
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); } } }
分析:存在缺点:第一左子树的最右边的节点的情况处理不到,分析貌似用深搜不行
leetcode116:Populating Next Right Pointers in Each Node
标签:
原文地址:http://www.cnblogs.com/savageclc26/p/4812811.html