[LeetCode] Binary Tree Upside Down
Posted apanda009
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] 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) { if (root == null) return null; TreeNode parent = root, left = root.left, right = root.right; if (left != null) { TreeNode ret = UpsideDownBinaryTree(left); left.left = right; left.right = parent; return ret; } return root; }
public TreeNode UpsideDownBinaryTree(TreeNode root) { TreeNode node = root, parent = null, right = null; while (node != null) { TreeNode left = node.left; node.left = right; right = node.right; node.right = parent; parent = node; node = left; } return parent; }
以上是关于[LeetCode] Binary Tree Upside Down的主要内容,如果未能解决你的问题,请参考以下文章
[Leetcode] Binary search tree --Binary Search Tree Iterator
Leetcode[110]-Balanced Binary Tree
[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree