LeetCode-- binary 2-- use recursion to solve the tree problem

LeetCode-- binary 2-- use recursion to solve the tree problem

In the previous section, we've covered how to use recursive solution to traverse the tree.
Recursion is one of the most effective and most common way to solve the problem tree.
We know that the tree can be defined recursively as a node (root), which includes a value and a pointer to a list of pointers to other nodes. Recursion is one of the characteristics of the tree.
Therefore, many tree problem can be solved by recursively.
For each level of recursion, we can only focus on the issue within a single node, and calls the function by recursion to solve the problem of its child nodes.
In general, we can " top-down " or " bottom-up " of recursion to solve the tree problem.

Top-down solutions

"Top-down" means that each recursive level, we will first access node to calculate some values and recursive function calls to pass these values to the children.
Therefore, the "top-down solutions it can be considered a preorder traversal of the former.
In particular, the principle of recursive functions top_down (root, params) is this:

1. return specific value for null node
2. update the answer if needed                      // anwer <-- params
3. left_ans = top_down(root.left, left_params)      // left_params <-- root.val, params
4. right_ans = top_down(root.right, right_params)   // right_params <-- root.val, params
5. return the answer if needed                      // answer <-- left_ans, right_ans

For example, consider this question: == Given a binary tree, look for its maximum depth ==.

We know the depth of the root node is 1.
For each node, if we know the depth of a node, then we will know the depth of its child nodes.
Therefore, when the function is called, the depth of the node passed as a parameter, all nodes are aware of their own depth.
For leaf nodes, so we can get a final answer by updating the depth.
Here is a recursive function maximum_depth (root, depth) is pseudocode:

1. return if root is null
2. if root is a leaf node:
3.      answer = max(answer, depth);         // update the answer if needed
4. maximum_depth(root.left, depth + 1)      // call the function recursively for left child
5. maximum_depth(root.right, depth + 1)     // call the function recursively for right child
C ++ code
int answer;            // don't forget to initialize answer before call maximum_depth
void maximum_depth(TreeNode* root, int depth) {
    if (!root) {
        return;
    }
    if (!root->left && !root->right) {
        answer = max(answer, depth);
    }
    maximum_depth(root->left, depth + 1);
    maximum_depth(root->right, depth + 1);
}

Bottom-up solutions

"Bottom-up" is another recursive method.
On each level of recursion, we first call the function recursively to all child nodes, then worth to answer by return and root itself.
This process can be seen as a post-order traversal.
Typically, "bottom-up" recursive function bottom_up (root) as follows:

1. return specific value for null node
2. left_ans = bottom_up(root.left)          // call function recursively for left child
3. right_ans = bottom_up(root.right)        // call function recursively for right child
4. return answers    

Let's continue to discuss the issue on the front of the maximum depth of the tree, but a different way of thinking:
for a single node of the tree, to a maximum depth x node itself is the root of the subtree is how much?
If we know a root node, its left child is the root of the maximum depth is l and its right child to the maximum depth of the root is r, if we can answer the previous question?
Of course, we can choose the maximum between them, plus 1 to obtain the maximum depth of the sub-root of the tree is located.
That is, x = max (l, r) + 1.
This means that for an answer after each node, we can solve the problem in its child nodes.
Therefore, we can use "bottom-up".
The following is a recursive function maximum_depth (root) is pseudocode:

return 0 if root is null                 // return 0 for null node
2. left_depth = maximum_depth(root.left)
3. right_depth = maximum_depth(root.right)
4. return max(left_depth, right_depth) + 1  // return depth of the subtree rooted at root
C ++ code
int maximum_depth(TreeNode* root) {
    if (!root) {
        return 0;                                 // return 0 for null node
    }
    int left_depth = maximum_depth(root->left);
    int right_depth = maximum_depth(root->right);
    return max(left_depth, right_depth) + 1;      // return depth of the subtree rooted at root
}

The maximum depth of the binary tree

 struct TreeNode {
     int val;
     TreeNode *left;
     TreeNode *right;
     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 };
 
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL)
            return 0;
        int left_depth = maxDepth(root->left);
        int right_depth = maxDepth(root->right);
        return max(left_depth,right_depth)+1;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int ans = 0 ;
    int maxDepth(TreeNode* root) {  
        int dep = 1;
        helper(root , dep);
        return ans;
    }
    void helper(TreeNode* root ,int depth)
    {
        if(root == NULL)
            return ;
        if (root->right == NULL && root->left == NULL)
            ans = max(ans , depth);
        if(root->right != NULL)
            helper(root->right,depth+1);
        if (root-> left != NULL)
            helper(root->left, depth+1);
    }
};

Symmetrical binary tree

The original idea is traversed by the sequence, whether fancy preorder vector equal inclusive.
But the code does not pass all the tests

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        vector<int> ans;
        inorder(root,ans);
        int back = ans.size();
        for(int i = 0; i <= back/2 ; i++)
        {
            cout << ans[i] << endl;
            if(ans[i] != ans[back-i-1])
                return false;
        }
        return true;
    }
    
    void inorder( TreeNode* root, vector<int> &order )
    {
        if(root == NULL)
        {
            return;
        }

        if (root->left != NULL){
            inorder(root->left,order);
        }
        
        order.push_back(root->val);
        
        if(root->right != NULL){
            inorder(root->right,order);
        }
        
    }
};

Conversion idea:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSymmetric(TreeNode* root) {
        if (root == NULL)
            return true;
        return helper(root->left , root->right);
        
    }
    
    bool helper (TreeNode* A,TreeNode* B)
    {
        if ( A == NULL && B == NULL)
            return true;
        if (A == NULL || B == NULL)
            return false;
        if (A->val != B->val)
            return false;
        return (helper(A->right,B->left)&&helper(A->left,B->right));
    }
};

Path sum

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    bool hasPathSum(TreeNode* root, int sum) {
        return helper(root,sum);
    }
    bool helper(TreeNode* cur, int sum)
    {
        if (cur == NULL)
            return false;
        if( cur->val == sum && cur->left == NULL && cur->right == NULL)
            return true; 
        return (helper(cur->left , sum - cur->val) || helper(cur->right,sum - cur->val) );
    }
};

Logic: all paths in the binary tree, whether a value equal to the target value

  1. From the top down, when the time came leaf node to detect whether the target value

Guess you like

Origin www.cnblogs.com/jiangxinyu1/p/12284978.html