【Leetcode】Flatten Binary Tree to Linked List
2015-11-22 11:00
330 查看
题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/
题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
The flattened tree should look like:
思路:
递归处理每个结点,如果结点左孩子为空,则无需处理。否则先将结点右孩子挂到左孩子最右边的子孙结点,然后将左孩子挂到右边,左边置空。注意,叶结点无需处理,要从叶的父结点开始处理。
算法:
题目:
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
思路:
递归处理每个结点,如果结点左孩子为空,则无需处理。否则先将结点右孩子挂到左孩子最右边的子孙结点,然后将左孩子挂到右边,左边置空。注意,叶结点无需处理,要从叶的父结点开始处理。
算法:
public void flatten(TreeNode root) { if (root == null) return; flatten(root.left); flatten(root.right); TreeNode p = root; // 递归到叶的父结点,因为叶结点不需要处理 if (p.left == null) {// 左孩子为空,无需处理 return; } p = p.left; while (p.right != null) // 找到p的左孩子最右边的结点 t p = p.right; p.right = root.right;// p的右孩子连到 t的右结点 root.right = root.left; root.left = null; }
相关文章推荐
- 点击蒙版或return隐藏键盘 ios
- 一个用于部署应用的ant脚本
- 【iOS】自定义导航栏(一)
- android中实现view可以滑动的六种方法
- 虚拟地址、逻辑地址、线性地址、物理地址
- Qt Qt4#include <QtGui>包含常用的头文件在Qt5中无效
- 如何在Cocos2D游戏中实现A*寻路算法(三)
- 如何在Cocos2D游戏中实现A*寻路算法(三)
- 如何在Cocos2D游戏中实现A*寻路算法(三)
- 《0day安全》学习笔记3——栈溢出实践
- opencv 报错:fatal error C1083: 无法打开包括文件: “stdafx.h”: No such file or directory
- HDU2639 01背包的第K最优决策
- Ubuntu 14.04 安装Virtualbox No suitable module for running kernel found
- SQL Server 中关于EXCEPT和INTERSECT的用法
- 【ZJOI2015】【BZOJ3926】诸神眷顾的幻想乡
- Genymotion启动时出现错误,virtualization engine not found,
- Oracle并行详解
- HDU 5568:sequence2 大数+DP
- HDU 5568:sequence2 大数+DP
- HDU1039