leetcode: (41) Populating Next Right Pointers in Each Node
2015-09-05 21:20
841 查看
【Question】
Given a binary tree
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
Initially, all next pointers are set to
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,
After calling your function, the tree should look like:
方法一:题目给出的是满二叉树,通过层序遍历,将pow(2,n)-1位置的结点的->next设NULL,其他的结点指向下一次将要遍历的结点
方法二:
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 / \ / \
方法一:题目给出的是满二叉树,通过层序遍历,将pow(2,n)-1位置的结点的->next设NULL,其他的结点指向下一次将要遍历的结点
* Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { queue<TreeLinkNode*> que; TreeLinkNode *p; p=root; if(p==NULL) return; que.push(p); int flag=1; int count=0; while(!que.empty()) { count++; p=que.front(); que.pop(); if(count==(pow(2,flag)-1)) {flag++;p->next=NULL;} else p->next=que.front(); if (p->left==NULL) continue; que.push(p->left); que.push(p->right); } } };这种方法开辟了额外的空间。
方法二:
class Solution { public: void connect(TreeLinkNode *root) { if(NULL == root) return; TreeLinkNode* curLev; while(root -> left != NULL){ curLev = root; while(curLev != NULL){ curLev -> left -> next = curLev -> right; if(curLev -> next != NULL) curLev -> right -> next = curLev -> next -> left; curLev = curLev -> next; } root = root -> left; } } };
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- C++非递归队列实现二叉树的广度优先遍历
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)
- JavaScript数据结构和算法之二叉树详解
- java使用归并删除法删除二叉树中节点的方法
- Java中二叉树数据结构的实现示例
- python数据结构之二叉树的建立实例
- python数据结构树和二叉树简介
- python数据结构之二叉树的统计与转换实例