111.Populating Next Right Pointers in Each Node
2016-04-17 08:51
363 查看
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:
Subscribe to see which companies asked this question。
分析:给定一个完全二叉树,给每个结点加上其可以指向所在层的右边结点,没有的话则指向null。
首先按层找到每一层的结点,然后让每个结点指向其右边的结点。
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
Subscribe to see which companies asked this question。
分析:给定一个完全二叉树,给每个结点加上其可以指向所在层的右边结点,没有的话则指向null。
首先按层找到每一层的结点,然后让每个结点指向其右边的结点。
/** * 给定一个完全二叉树,给每个结点加上其可以指向所在层的右边结点,没有的话则指向null。 * Step1:按层获取每层的结点; * Step2:每层的结点right指向其右边结点,最右边指向null。 * @date 20160417 */ public void connect(TreeLinkNode root) { /*如果根结点为空则直接返回*/ if(root == null){ return; } List<TreeLinkNode> currentlist = new ArrayList<TreeLinkNode>();//存放当前层的结点,初始化时放入根结点 List<TreeLinkNode> nextlist = new ArrayList<TreeLinkNode>();//当前层的孩子结点层 currentlist.add(root); TreeLinkNode node ; while(currentlist.size()!=0){ int size = currentlist.size(); /*依次遍历当前层中每个结点,并把拿到的结点的next指向其下一个结点,同时把当前结点的孩子结点放到孩子层*/ int i=0; for(;i<size-1;i++){ node = currentlist.get(i); node.next = currentlist.get(i+1); if(node.left!=null){ nextlist.add(node.left); } if(node.right!=null){ nextlist.add(node.right); } } node=currentlist.get(i); node.next =null;//当前层的最右边指向null if(node.left!=null){ nextlist.add(node.left); } if(node.right!=null){ nextlist.add(node.right); } currentlist.clear(); currentlist.addAll(nextlist); nextlist.clear(); }//end while }
相关文章推荐
- 【Node JS环境搭建及sublime Text 3配置Node Js环境】
- Nodejs Stream 数据流使用手册
- 用nodejs模拟请求发微博
- 【一天一道LeetCode】#19. Remove Nth Node From End of List
- 【一天一道LeetCode】#19. Remove Nth Node From End of List
- nodejs cms开源框架
- Node.js 文件模块(fs)模块介绍
- 配置nodejs环境
- 详细分析Node.js中的UDP模块
- node初识
- windows环境安装nodejs
- node.js 学习笔记003 :使用superagent和cheerio实现简单网页爬虫
- ubuntu 源码安装nodejs
- 安装Node.js和Electron
- nodejs爬虫编码问题
- node.js 学习笔记002 : 使用utility实现字符串加密
- Node.js 从入门到茫然系列——入门篇
- node.js 学习笔记001 :Hello,world !
- leetcode 19:Remove Nth Node From End of List
- cesium学习1--环境搭建和配置