https://leetcode-cn.com/problems/binary-tree-upside-down/
给定一个二叉树,其中所有的右节点要么是具有兄弟节点(拥有相同父节点的左节点)的叶节点,要么为空,将此二叉树上下翻转并将它变成一棵树, 原来的右节点将转换成左叶节点。返回新的根。
例子:
输入: [1,2,3,4,5]
1 / \ 2 3 / \ 4 5
输出: 返回二叉树的根 [4,5,2,#,#,3,1]
4 / \ 5 2 / \ 3 1
这道题属于阅读理解题。
由于题目给出了很多简化,例如给定的输入肯定满足题目要求,因此可以省去大量时间。
分为两步:1. 反转最左侧链表;2. 将原本右孩子(经过第一步后为左孩子)提高一层。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* upsideDownBinaryTree(TreeNode* root) {
if( !root)
return NULL;
stack<TreeNode*> record;
TreeNode* next = root;
//压栈
while( root){
next = root->left;
root->left = NULL, root->left = root->right, root->right = NULL;
record.push( root);
root = next;
}
//反转最左侧
root = record.top();
while( !record.empty()){
TreeNode* now = record.top();
record.pop();
if( !record.empty())
now->right = record.top();
}
//提高左孩子
TreeNode* now = root;
next = root->right;
while( next){
now->left = next->left, next->left = NULL;
now = next, next = next->right;
}
return root;
}
};