2017-11-11 236 views
-1

问:关于使用递归和返回的二叉搜索树遍历,我有疑问。我必须按照按升序排列键的BST,然后“倒转”它,这样所有键都按降序排列,正如您在图片中看到的那样。使用递归进行二叉搜索树遍历

根据我的下面的代码的了解,我认为步骤是:

->reverseKeys (10) ->reverseKeys (2) 
    ->reverseKeys (null): return 
    ->reversekeys(null): return 
    ->BSTNODE <T> ptr = root.left; 
    ->root.left = root.right; 
    ->root.right = ptr; 

我想我误解的代码。有人能够扩展这个代码如何将左边的图片更改为右边?我将不胜感激任何帮助。

25     25 
/\    /\ 
10 40  ---> 40 10 
/\ /\   /\/\ 
2 20 30 45  45 30 20 2 
/ \   / \ 
15 35   35 15 

public static <T extends Comparable<T>> 
void reverseKeys(BSTNode<T> root) { 
    if (root == null) { 
     return; 
    } 
    reverseKeys(root.left); 
    reverseKeys(root.right); 
    BSTNode<T> ptr = root.left; 
    root.left = root.right; 
    root.right = ptr; 
} 

回答

0

检查BST - 反向下面的代码

public void traverse (Node root){ // Each child of a tree is a root of its subtree. 
    if (root.left != null){ 
     traverse (root.left); 
    } 
    System.out.println(root.data); 
    if (root.right != null){ 
     traverse (root.right); 
    } 
} 

// Search with a valid node returned, assuming int 

public Node traverse (Node root, int data){ // What data are you looking for again? 
    if(root.data == data) { 
     return root; 
    } 
    if (root.left != null){ 
     return traverse (root.left, data); 
    } 
    if (root.right != null){ 
     return traverse (root.right, data); 
    } 
    return null; 
} 
1

这些线路只是交换左,右子树的节点序遍历(RVL)。由于对方法的递归调用,当方法执行时,每个节点都有左右子树交换。

BSTNode<T> ptr = root.left; 
root.left = root.right; 
root.right = ptr;