0
点赞
收藏
分享

微信扫一扫

5.4.6每个节点的右向指针


文章目录

  • ​​1.题目​​
  • ​​2.代码​​

1.题目

  • ​​题目要求​​
  • eg:

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

  • 思路:是完美二叉树,所有的所有叶子节点都处于相同层次,且每个父节点都有2个子节点
  • 这道题实际上是树的层序遍历BFS的应用

2.代码

struct Node{
struct Node *left;
struct Node *right;
struct Node *next;
Node(Node* left,Node* right,Node* next) : left(NULL),right(NULL), next(NULL) {}
};

递归法
class Soulution{
public:
Node* connect(Node* root)
{
if !(root) return 0;
if (root->left) root->left->next=root->right;
if (root-right) root->right=root->next?root->next->left:NULL;
connect(root->left);
connect(root->right);
return root;
}
};

迭代法
class Soulution{
public:
Node* connect(Node* root)
{
queue<Node*> qu;
qu.push(root);
while (!qu.empty())
{
for (int i=que.size();i>0;--i)
{
Node* node=qu.front();qu.pop();
node->next=qu.front();
}

if (node->left) qu.push(node-left);
if (node->right) qu.push(node-right);
}
return root;
}


举报

相关推荐

0 条评论