有人可以向我解释这个二叉树的递归代码吗?

时间:2018-04-20 12:41:35

标签: recursion binary-tree

我正试图解决这个问题“二叉树颠倒”。例如,如果我们有二叉树:

    1
   / \
  2   3
 / \
4   5

运行我的功能后,它将变为:

   4
  / \
 5   2
    / \
   3   1 

我得到了以下递归代码,但无法理解// 1和// 5之间的步骤;

public TreeNode UpsideDownBinaryTree(TreeNode root)
{
    if (root == null) return null;

    TreeNode parent = root, left = root.left, right = root.right;
    if (left != null)
    {
        TreeNode ret = UpsideDownBinaryTree(left); //1
        left.left = right;   //2
        left.right = parent; //3
        return ret;          //4
    }
    return root;             //5
}

有人可以向我详细解释每个步骤在这里做了什么吗?另外,为什么我们有两个单独的回报:return retreturn root

我知道如何对常规数组,列表和一些二叉树进行递归。但是这种递归逻辑似乎与我之前所知的不同。我甚至使用IDE来逐步完成,但仍然无法完全理解它。

此问题我还有以下迭代代码。我能理解这段代码。它从根目录扫描树离开。但对于递归代码,它是从root用户扫描树离开并从离开到构建新树的根?我理解正确吗?

public TreeNode UpSideDownTree_Iterative(TreeNode root)
    {
        TreeNode node = root,parent = null,right = null;
        while (node != null) {
            TreeNode left = node.left;
            node.left = right;
            right = node.right;
            node.right = parent;
            parent = node;
            node = left;
        }
        return parent;
}

1 个答案:

答案 0 :(得分:0)

从最后一次调用向后看它可能会有所帮助 该方法以左节点递归调用,因此将使用节点1,2和4调用 最后左边的节点(叶子)是节点4: 见评论:

//when invoked with node 4 
public TreeNode UpsideDownBinaryTree(TreeNode root)
{
    if (root == null) return null;

    TreeNode parent = root;      //node 4 
    TreeNode leftNode = root.left;   //null  
    TreeNode rightNode = root.right; //null  

    if (leftNode != null) 
    {
        //not executed
        TreeNode ret = UpsideDownBinaryTree(leftNode); //invoke with 2
        leftNode.left = rightNode; //left of node 2 becomes node 3
        leftNode.right = parent; //right of node 2 becomes 1
        return ret;          
    }
    return root;             //returned. The leaf becomes new root
}

让我们看一下上一步:它返回上一次调用(节点2):

//when invoked with node 2 
public TreeNode UpsideDownBinaryTree(TreeNode root)
{
    if (root == null) return null;

    TreeNode parent = root;       //node 2 
    TreeNode leftNode = root.left;   //node 4  
    TreeNode rightNode = root.right; //node 5 

    if (leftNode != null) 
    {
        TreeNode ret = UpsideDownBinaryTree(leftNode); //invoke with node 4
                                                       //as seen above return 
                                                       //value is node 4 
                                                       //which is the new root
        leftNode.left = rightNode; //left of node 4 becomes node 5
        leftNode.right = parent; //right of node 4 becomes 2
        return ret; //node 4 returned, the new root        
    }
    return root;            
}

第一次调用(节点1)与节点2非常相似。