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
思路:
起始对于每一个节点,相应的操作为:
p.left = parent.right;
p.right = parent;
public class Solution { public TreeNode upsideDownBinaryTree(TreeNode root) { TreeNode p = root, parent = null, parentRight = null; while (p!=null) { TreeNode left = p.left; p.left = parentRight; parentRight = p.right; p.right = parent; parent = p; p = left; } return parent; } }
Bottom up approach:
Although the code for the top-down approach seems concise, it is actually subtle and there are a lot of hidden traps if you are not careful. The other approach is thinking recursively in a bottom-up fashion. If we reassign the bottom-level nodes before the upper ones, we won’t have to make copies and worry about overwriting something. We know the new root will be the left-most leaf node, so we begin the reassignment here.
相关推荐
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。