Binary tree problem-solving ideas

introduction

  Recursive binary tree itself is generated, so the time to address related issues, first is to use recursion to do ,

       However, because of time and space algorithm, so try to convert recursive iterations to do .

Recursive problem-solving ideas

  Recursion is in the process of running call your own .

    Recursive configuration conditions should have,:

    1. The child must issue the original problem is the same thing , and the more simple ;
    2. Do not unlimited calling itself, must have exit , simplify the situation for non-recursive processing.

      Highlights: 

              1. The first thing to do is to determine their smallest units and to write it down;

                  This is because the sub-problem and the original problem is the same thing, so make sure the child thing, the original problems will be identified

        2. Identify the problem child of the termination conditions ;

                 This is because the recursive ultimately need to end, that is the result of a return, so you have to determine the minimum unit need to return any results (return what)

                And he's what the end conditions .

            3. Locate the original question of how to convert a sub-issue of the conditions the way :

                 Usually there is such a form to enter the return A + B

Therefore, the above steps are summarized as follows: to find the smallest problem, the smallest problem how to stop, turn a small problem big problem; (programming idea is to write from bottom to top , from top to bottom to achieve the implementation of the self)

 

Recursive Case:
 
    Given a binary tree and a destination and determines whether the root node to the leaf node in the tree path exists, all the nodes on this route, and equal to the target value is added.


实现代码:
/*
* * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { int count = 0; return preOder(root, count,sum); } private Boolean preOder(TreeNode root, int sum,int expect){ if(root == null){ return to false ; } SUM + = root.val; // . 1, the minimum unit, do IF ( root.left == null && root.right == null ) { // 2, the termination condition return SUM == Expect; } return preOder (root.left, SUM, Expect) || preOder (root.right, SUM, Expect); /// . 3, a large problem into sub-problems } }

 

 

Non-recursive ideas

 

    

 

Guess you like

Origin www.cnblogs.com/helloqiufei/p/11482975.html