LeetCode 156. Binary Tree Upside Down

本文介绍了一种特殊的二叉树翻转算法,即将右节点变为左叶子节点,原根节点变为新的右节点。提供了递归和迭代两种实现方式,并详细解释了每一步操作的目的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路:
1.关于树的问题,大致就是recursive 和iterative两种方式去遍历或者修改树的node,这里用recursive。题意有些模糊,先搞清题意:将左节点变成新的根节点,把右节点变成新的左节点,把就的根节点变成新的右节点,即:遍历后根据node位置修改指针。

TreeNode *upsideDownBinaryTree(TreeNode *root) {
    //recursive
    if(!root||!root->left) return root;
    TreeNode* l=root->left,*r=root->right;
    TreeNode* newRoot=upsideDownBinaryTree(l);
    l->left=r;//这两行是添加新的左右node指针
    l->right=root;
    root->left=NULL;//这两行是把原来根节点的指针清空
    root->right=NULL;
    return newRoot;
}
  1. 还可以用iterative,
    参考http://www.cnblogs.com/grandyang/p/5172838.html
TreeNode *upsideDownBinaryTree(TreeNode *root) {
    //recursive,因为给定的tree经过flip后很像reverse the linked list的结果,所有在linkedlist中用pre,cur,next三个指针的方法可以借鉴到这里

    if(!root||!root->left) return root;
    TreeNode* cur=root,*pre=NULL,*next=NULL,oldRight=NULL;
    while(cur){
        next=cur->left;
        cur->left=oldRight;
        oldRight=cur->right;
        cur->right=pre;
        pre=cur;
        cur=next;
    }
    return pre;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值