倒置二叉树(递归)

问题描述 投票:0回答:4

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

创建二叉树

#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) 

输出:

伪代码:

#def invert_tree(nodes, root)

#Stop recursion if tree is empty

#swap left subtree with right subtree

#invert left subtree

#invert right subtree
python binary-tree
4个回答
1
投票

我找到答案了

nodes = [[4], [7, 2], [1, 3, 6, 9]]

递归

newlist1 = []
def reverse_tree(lst):
    if not lst:
        return
    newlist1.append(lst.pop(0)[::-1])
    reverse_tree(lst)

reverse_tree(nodes)

print(newlist1)

输出:

[[4], [2, 7], [9, 6, 3, 1]]

使用列表理解

#ListComprehension
newlist2 = [x[::-1] for x in nodes]
print(newlist2)

输出:

[[4], [2, 7], [9, 6, 3, 1]]

0
投票
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.

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

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
投票
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode() {}
     *     TreeNode(int val) { this.val = val; }
     *     TreeNode(int val, TreeNode left, TreeNode right) {
     *         this.val = val;
     *         this.left = left;
     *         this.right = right;
     *     }
     * }
     */
     //recursion problem, swap every left with the right node in postorder 
     class Solution {
          public TreeNode invertTree(TreeNode root) {
               if (root == null) return null;
               if(root.left == null && root.right == null) {
                    return root;
               }
               invertTree(root.left);
               invertTree(root.right);
               TreeNode temp = root.left;
               root.left = root.right;
               root.right = temp;
               return root;
          }
     }

在 Leetcode 上使用 Java 格式尝试此代码,您将通过..


-1
投票

TreeNode* 反转(TreeNode* 树){

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;

}

© www.soinside.com 2019 - 2024. All rights reserved.