首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反演二叉树(递归)

反演二叉树(递归)
EN

Stack Overflow用户
提问于 2020-12-11 10:55:27
回答 3查看 2.5K关注 0票数 0

我不知道如何输出反向二叉树。这就是我到目前为止想出的+我的伪代码。

创建二叉树

代码语言:javascript
复制
#Creating the binary tree
from binarytree import build
from binarytree import tree
   
# List of nodes 
nodes =[4, 2, 7, 1, 3, 6, 9] 
  
# Builidng the binary tree 
binary_tree = build(nodes) 
print('Binary tree from example :\n ', 
      binary_tree) 
  
# Getting list of nodes from 
# binarytree 
print('\nList from binary tree :',  
      binary_tree.values) 

输出:

伪码:

代码语言:javascript
复制
#def invert_tree(nodes, root)

#Stop recursion if tree is empty

#swap left subtree with right subtree

#invert left subtree

#invert right subtree
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-12-11 13:22:33

我找到了一个答案

代码语言:javascript
复制
nodes = [[4], [7, 2], [1, 3, 6, 9]]

递归

代码语言:javascript
复制
newlist1 = []
def reverse_tree(lst):
    if not lst:
        return
    newlist1.append(lst.pop(0)[::-1])
    reverse_tree(lst)

reverse_tree(nodes)

print(newlist1)

输出:

代码语言:javascript
复制
[[4], [2, 7], [9, 6, 3, 1]]

使用列表理解的

代码语言:javascript
复制
#ListComprehension
newlist2 = [x[::-1] for x in nodes]
print(newlist2)

输出:

代码语言:javascript
复制
[[4], [2, 7], [9, 6, 3, 1]]
票数 1
EN

Stack Overflow用户

发布于 2020-12-11 15:21:51

代码语言:javascript
复制
Your question isn't clear;

From what I understood:

To print the nodes of an inverted tree:
    Try Level order traversal, more precisely you can use the BFS method.

或者:如果您想反转二叉树;我的方法(给定树的根节点):

代码语言:javascript
复制
def invert_tree(self, root):
    if root:
        temp=root.left
        root.left = self.invert_tree(root.right)
        root.right = self.inver_tree(temp)
        return root

由于树中的每个节点都被访问过一次,所以时间复杂度是O(n)。

票数 0
EN

Stack Overflow用户

发布于 2022-03-27 01:25:11

树节点*倒置(树节点*树){

代码语言:javascript
复制
if(tree == NULL) return NULL;

TreeNode* temp;
temp = tree->left;
tree->left = tree->right;
tree->right = temp;

Invert(tree->left);
Invert(tree->right);
return tree;

}

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65249988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档