欢迎来到代码驿站!

C代码

当前位置:首页 > 软件编程 > C代码

C++实现LeetCode(156.二叉树的上下颠倒)

时间:2022-08-28 09:29:40|栏目:C代码|点击:

[LeetCode] 156. 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:

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  

Clarification:

Confused what [4,5,2,#,#,3,1] means? Read more below on how binary tree is serialized on OJ.

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
/ \
2   3
/
4
\
5

The above binary tree is serialized as [1,2,3,#,#,4,#,#,5].

这道题让我们把一棵二叉树上下颠倒一下,而且限制了右节点要么为空要么一定会有对应的左节点。上下颠倒后原来二叉树的最左子节点变成了根节点,其对应的右节点变成了其左子节点,其父节点变成了其右子节点,相当于顺时针旋转了一下。对于一般树的题都会有迭代和递归两种解法,这道题也不例外,先来看看递归的解法。对于一个根节点来说,目标是将其左子节点变为根节点,右子节点变为左子节点,原根节点变为右子节点,首先判断这个根节点是否存在,且其有没有左子节点,如果不满足这两个条件的话,直接返回即可,不需要翻转操作。那么不停的对左子节点调用递归函数,直到到达最左子节点开始翻转,翻转好最左子节点后,开始回到上一个左子节点继续翻转即可,直至翻转完整棵树,参见代码如下:

解法一:

class Solution {
public:
    TreeNode *upsideDownBinaryTree(TreeNode *root) {
        if (!root || !root->left) return root;
        TreeNode *l = root->left, *r = root->right;
        TreeNode *res = upsideDownBinaryTree(l);
        l->left = r;
        l->right = root;
        root->left = NULL;
        root->right = NULL;
        return res;
    }
};

下面我们来看迭代的方法,和递归方法相反的时,这个是从上往下开始翻转,直至翻转到最左子节点,参见代码如下:

解法二:

class Solution {
public:
    TreeNode *upsideDownBinaryTree(TreeNode *root) {
        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;
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/156

类似题目:

Reverse Linked List

参考资料:

https://leetcode.com/problems/binary-tree-upside-down/

https://leetcode.com/problems/binary-tree-upside-down/discuss/49412/Clean-Java-solution

https://leetcode.com/problems/binary-tree-upside-down/discuss/49432/Easy-O(n)-iteration-solution-Java

https://leetcode.com/problems/binary-tree-upside-down/discuss/49406/Java-recursive-(O(logn)-space)-and-iterative-solutions-(O(1)-space)-with-explanation-and-figure

上一篇:C语言 超详细顺序表的模拟实现实例建议收藏

栏    目:C代码

下一篇:C语言宏函数container of()简介

本文标题:C++实现LeetCode(156.二叉树的上下颠倒)

本文地址:http://www.codeinn.net/misctech/212109.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有