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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if (root == null) return null;
TreeNode left = null, right = null;
TreeNode nextRoot = root.left, nextLeft = root.right;
while (root != null) {
root.left = left;
root.right = right;
left = nextLeft;
right = root;
root = nextRoot;
if (root == null) break;
nextRoot = root.left;
nextLeft = root.right;
}
return right;
}
}
分享到:
相关推荐
javascript js_leetcode题解之156-binary-tree-upside-down.js
java java_leetcode-107-binary-tree-level-order-traversal
java java_leetcode-102-binary-tree-level-order-traversal
java java_leetcode-110-balanced-binary-tree
java java_leetcode-maximum-depth-of-binary-tree
java java_leetcode-114-flatten-binary-tree-to-linked-list
java java_leetcode-99-recover-binary-search-tree
java java_leetcode-111-minimum-depth-of-binary-tree
java java_leetcode-105-construct-binary-tree-from-preorder-and-inorde
python python_leetcode题解之156_Binary_Tree_Upside_Down.py
java java_leetcode-101-symmetric-tree
java java_leetcode-100-same-tree
python python_leetcode_109_Convert_Sorted_List_to_Binary_Search_Tree
《在IDE中高效进行LeetCode练习:leetcode-editor的深度解析》 在编程学习与技能提升的过程中,LeetCode作为一款广受欢迎的在线编程挑战平台,帮助众多开发者锻炼算法思维,提高编程能力。而为了进一步提升练习体验...
c语言入门 c语言_leetcode题解543-diameter-of-binary-tree.c
leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源leetcode-习题集资源
leetcode-cli-plugins leetcode-cli 的第 3 方插件。 什么是 如何使用 如何使用 插件 名称 描述 增强的命令 按公司或标签过滤问题 list 不要在同一台计算机上使 Chrome 的会话过期 login 不要在同一台计算机上使 ...
"leetcode-tag-Tree" 指的是 LeetCode 上与“树”相关的标签,这通常意味着这些题目涉及到数据结构中的树型结构。树是一种非线性的数据结构,由若干个节点(或称为顶点)和连接这些节点的边组成,每个节点都可能有零...
在IDE中解决LeetCode问题,支持leetcode.com与leetcode-cn.com,满足基本的做题需求。 理论上支持: IntelliJ IDEA PhpStorm WebStorm PyCharm RubyMine AppCode CLion GoLand DataGrip Rider MPS Android Studio。