题目描述
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:
Input: [1,2,3,4,5]
1
/ \
2 3
/ \
4 5
Output: return the root of the binary tree [4,5,2,#,#,3,1]
4
/ \
5 2
/ \
3 1
算法1
(枚举) $O(n)$
题意是当前node与左节点的父子关系颠倒,node的右节点变为node左节点的左节点。所以需要四个指针:cur指向当前节点,pre指向父节点,tmp指向右节点,next指向左节点。从next指针开始迭代。
时间复杂度
遍历一次O(n)
空间O(1)
参考文献
C++ 代码
class Solution {
public:
TreeNode* upsideDownBinaryTree(TreeNode* root) {
if(!root) return NULL;
TreeNode *cur=root, *pre=NULL, *next=NULL, *tmp=NULL;
while(cur)
{
next=cur->left;
cur->left=tmp;
tmp=cur->right;
cur->right=pre;
pre=cur;
cur=next;
}
return pre;
}
};