[LeetCode] Binary Tree Upside Down

Problem Description:

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  

This problem seems to be tricky at first glance. Well, let's analyze the above example carefully. We can immediately see that there is a reversed correspondence between the two trees, which are the 1 -> 2 -> 4 in the tree above and the 4 -> 2 -> 1 in the tree below. Moreover, for each node along the left path 1 -> 2 -> 4 in the original tree, its new left child is its original right sibling and its new right child is its original parent.

Now we can write down the following recursive code.

复制代码
 1 class Solution {
 2 public:
 3     TreeNode* upsideDownBinaryTree(TreeNode* root) {
 4         return upsideDown(root, NULL, NULL);    // start from root
 5     }
 6 private:
 7     TreeNode* upsideDown(TreeNode* node, TreeNode* parent, TreeNode* sibling) {
 8         if (!node) return parent;
 9         TreeNode* left = node -> left;          // old left child
10         TreeNode* right = node -> right;        // old right child
11         node -> left = sibling;                 // new left child is old right sibling
12         node -> right = parent;                 // new right child is old parent
13         return upsideDown(left, node, right);   // node is left's parent and right is left's sibling
14     }
15 };
复制代码

The above recursive code can be turned into the following iterative code easily.

复制代码
 1 class Solution {
 2 public:
 3     TreeNode* upsideDownBinaryTree(TreeNode* root) {
 4         TreeNode* run = root;
 5         TreeNode* parent = NULL;
 6         TreeNode* sibling = NULL;
 7         while (run) {
 8             TreeNode* left = run -> left;   // old left child
 9             TreeNode* right = run -> right; // old right child
10             run -> left = sibling;          // new left child is old right sibling
11             run -> right = parent;          // new right child is old parent
12             parent = run;
13             run = left;
14             sibling = right;
15         }
16         return parent;
17     }
18 };
复制代码

 

posted @   jianchao-li  阅读(252)  评论(0)    收藏  举报
编辑推荐:
· 长文讲解 MCP 和案例实战
· Hangfire Redis 实现秒级定时任务,使用 CQRS 实现动态执行代码
· Android编译时动态插入代码原理与实践
· 解锁.NET 9性能优化黑科技:从内存管理到Web性能的最全指南
· 通过一个DEMO理解MCP(模型上下文协议)的生命周期
阅读排行:
· 工良出品 | 长文讲解 MCP 和案例实战
· 一天 Star 破万的开源项目「GitHub 热点速览」
· 多年后再做Web开发,AI帮大忙
· 记一次 .NET某旅行社酒店管理系统 卡死分析
· 别再堆文档了,大模型时代知识库应该这样建
点击右上角即可分享
微信分享提示