563. Recursive use of the slope of a binary tree

To be honest, recursion + backtracking is very simple and difficult. This sentence is the one I feel most deeply. Sometimes it is a very simple recursion in my brain, which is very troublesome to implement. Let ’s talk about the recursion of trees. It should be kept in mind, but how to solve specific problems, list the topics:

It feels good to do, that is, each node runs once the value of the left subtree minus the absolute value of the right subtree, but for this question, I start from the beginning, what will we encounter if we use recursion The problem? That is, we need to calculate the values ​​of the left and right subtrees of each node, then there will be some troubles, we may wish to think more, recursively from bottom to top, our last layer of nodes must be the absolute value of left-right,

In order not to allow the sum of the subtree nodes to be repeatedly calculated, we should return the sum of all nodes in the current tree.
That is, when a node gets the sum of the nodes returned by the child node, the slope of the node is calculated immediately, which can be stored in an instance variable, and then the tree of the current node is also returned upward as the root node. The sum of all nodes.
In this way, in the process of bottom-up, it continuously returns the sum of all nodes of the subtree, then calculates and accumulates the slope of the current node, and then returns the sum of the nodes of the current tree upward. After the slope of the root node is calculated, the recursive traversal ends, and the sum of the slopes of all nodes comes out.

Below we list the code:

        int tilt=0;
        public int findTilt(TreeNode root) {
            traverse(root);
            return tilt;
        }
        public int traverse(TreeNode root)
        {
            if(root==null )
                return 0;
            int left=traverse(root.left);
            int right=traverse(root.right);
            tilt+=Math.abs(left-right);
            return left+right+root.val;
        }

 

Published 17 original articles · praised 0 · visits 147

Guess you like

Origin blog.csdn.net/qq_33286699/article/details/105271630