- 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.
Example
Example1
Input: {1,2,3,4,5}
Output: {4,5,2,#,#,3,1}
Explanation:
The input is
1
/
2 3
/
4 5
and the output is
4
/
5 2
/
3 1
Example2
Input: {1,2,3,4}
Output: {4,#,2,3,1}
Explanation:
The input is
1
/
2 3
/
4
and the output is
4
2
/
3 1
{1,2,3,4,5}
解法1:递归。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode * upsideDownBinaryTree(TreeNode * root) {
if (!root || !root->left) return root;
TreeNode *left = root->left, *right = root->right;
TreeNode * result = upsideDownBinaryTree(root->left);
left->left = right;
left->right = root;
root->left = NULL;
root->right = NULL;
return result;
}
};
解法2:递归。跟解法1差不多。效率高些,因为省了root->left=NULL和root->right=NULL这两个操作。实际上只有真正的root需要设这个。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode * upsideDownBinaryTree(TreeNode * root) {
if (!root || !root->left) return root;
//TreeNode *left = root->left, *right = root->right;
TreeNode * result = dfs(root);
root->left = NULL;
root->right = NULL;
return result;
}
private:
TreeNode * dfs(TreeNode * root) {
if (!root || !root->left) return root;
TreeNode *left = root->left;
TreeNode *right = root->right;
TreeNode * result = dfs(root->left);
left->left = right;
left->right = root;
return result;
}
};
解法3:非递归。类似反转链表的迭代法。
如下图所示,其中pre, root和next类似于链表反转的pre, head和temp。这里不同的是还要为右节点加个tmp。
最后返回pre。

/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: the root of binary tree
* @return: new root
*/
TreeNode * upsideDownBinaryTree(TreeNode * root) {
if (!root || !root->left) return root;
TreeNode * pre = NULL;
TreeNode * tmp = NULL; //for right child
TreeNode * next = NULL; //for left child
while(root) {
next = root->left;
root->left = tmp;
tmp = root->right;
root->right = pre;
pre = root;
root = next;
}
return pre;
}
};
本文介绍了一种将特定形态的二叉树翻转的算法,通过递归和非递归方式实现,使右子节点变为左叶节点,返回新的根节点。提供了三种解法,包括两种递归方法和一种迭代方法。
6655

被折叠的 条评论
为什么被折叠?



