Binary Tree Upside Down
来源:互联网 发布:安卓windows开机动画包 编辑:程序博客网 时间:2024/06/07 11:19
https://oj.leetcode.com/problems/binary-tree-upside-down/
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:Given a binary tree
{1,2,3,4,5}
,1 / \ 2 3 / \4 5
return the root of the binary tree [4,5,2,#,#,3,1]
.
4 / \ 5 2 / \ 3 1
public TreeNode UpsideDownBinaryTree(TreeNode root)
这一题不是很难,原因就在与它的特殊的树的结构。也就是所有节点的右子树都只有一个节点。也就是实际上没有右子树的概念,只有右子节点。那么循环的做法就是从根节点不停往左节点往下遍历,将parent节点做为当前节点的右节点,兄弟节点作为当前节点的左节点。所以在每一层,你所需要保存的就是parent节点,兄弟节点(parent的右节点),以及下一层的左子节点。根据上述算法,给出解法如下:
public TreeNode UpsideDownBinaryTree(TreeNode root) { if(root == null) return null; TreeNode prev = root, neighbor = root.right, cur = root.left;//cur用来向左遍历,prev表示parent节点,neighbor表示兄弟节点 while(cur != null){ TreeNode cur_neighbor = cur.right, next = cur.left;//我们需要再改变树结构之前先行记录下一层的节点已经兄弟节点。 cur.right = prev; cur.left = neighbor; prev = cur; neighbor = cur_neighbor; cur = next; } root.left = null; root.right = null; return prev; }}
0 0
- Binary Tree Upside Down
- Binary Tree Upside Down
- Binary Tree Upside Down
- Binary Tree Upside Down
- Binary Tree Upside Down
- Binary Tree Upside Down
- Binary Tree Upside Down
- [Leetcode] Binary Tree Upside Down
- LeetCode Binary Tree Upside Down
- leetcode Binary Tree Upside Down
- [Leetcode] Binary Tree Upside Down
- leetcode--Binary Tree Upside Down
- [LeetCode156] Binary Tree Upside Down
- LeetCode-Binary Tree Upside Down
- [LeetCode156] Binary Tree Upside Down
- Leetcode Binary Tree Upside Down
- 156. Binary Tree Upside Down
- 156. Binary Tree Upside Down
- Ubuntu 下安装GTK
- iOS 获取去掉空格的字符串长度
- Java基础(面向对象二——static关键字、主函数定义和单例设计模式)
- 李彦宏两会提议建立“中国大脑”计划,希望国家将人工智能提升到国家高度
- 关于a标签点击周围会出现虚线
- Binary Tree Upside Down
- Stanford - Algorithms: Design and Analysis, Part 1 - Week 5 Assignment: Dijkstra
- stm32f4中通过dma采集adc
- 替换多个单词
- VBScript文件操作对象FileSystemObject大全
- c语言_数据结构_双向循环链表
- 机器学习常见算法汇总
- Ubuntu下安装httpsqs遇到的问题与解决
- op的形态 和自激