A brief application of recursion

First of all, here is a simple question that briefly verifies the idea of ​​writing a recursive question in this article I posted before  . I will use it to explain the idea of ​​​​this question:

The sword points to Offer 27 and method 226. Flip the binary tree

You are given the root node of a binary tree  root , flip the binary tree and return its root node. 

1. When is the data operated on?

After analyzing the problem, we found that the left and right subtrees of each node need to be exchanged. As long as we ensure that when exchanging the left and right subtrees of the current node, we do not operate the own node, then we can do either recursive operation or backtracking exchange. What I choose here is the backtracking operation, first recurse to the deepest point, and then backtrack to whichever node, just exchange its left and right subtrees.

2. What needs to be returned in a recursive function? 

 This is the analysis idea in  my article  about writing recursive questions :

Looking at this question, what we ultimately return is the head node of the flipped tree, and the operations of flipping nodes can be completed during the recursive process or the backtracking process, so we do not need to return any value (here is my Of course, there are other ideas that require return nodes, you can understand them by yourself), in summary, it belongs to the fourth situation;

3. Decide on the termination condition and what should we return?

The recursion termination situation of this question is that the recursion reaches the deepest part of the tree, that is, when the current node is null, return; just end this level of recursion. (Because we chose case 4 above, we don’t need to return the value and just end it directly)

To sum up, the code is as follows:

    public TreeNode mirrorTree(TreeNode root) {
        if (root==null){
            return null;
        }
        digui(root);//递归过程中对树结构操作,无需返回值
        return root;
    }

    void digui(TreeNode root) {
        if (root==null){
            return;
        }
        digui(root.left);
        digui(root.right);//递归函数在具体操作上面,属于先递归,回溯时操作数据
        TreeNode treeNode=root.left;
        root.left = root.right;
        root.right = treeNode;
        return;
    }

Guess you like

Origin blog.csdn.net/weixin_52394141/article/details/131334165
Recommended