Binary tree recursive algorithm to practice the type of summary

Recursive types

Points snapped in accordance with programming skills

First, the complex problem into two sub-problems

 1, balanced binary tree ( LeetCode title exam 110 )

From top to bottom : the balance factor calculated for each node (i.e., the height difference between the left and right sub-tree), it is determined whether the condition is satisfied.

Can be divided into two sub-problems: seeking height of the tree, through the tree and each node determines whether the condition

 

class Solution {
     public  Boolean isBalanced (the TreeNode the root) {
         IF (the root == null ) {
             return  to true ; 
        } the else {
             // determines whether the root node satisfies the balance factor 
            int ldepth = depth (root.left);
             int rdepth = depth ( root.right); 
            System.out.println (ldepth + "" + rdepth);
             iF (the Math.abs (ldepth - rdepth)>. 1 ) {
                 return  to false ; 
            } 
            // Analyzing left subtree meets balance factor
            IF (! {isBalanced (root.left))
                 return  to false ; 
            } 
            // determines whether the right subtree satisfy balance factor 
            IF (! isBalanced (root.right)) {
                 return  to false ; 
            } 
            return  to true ; 
        } 
    } 
    Private  int depth (the TreeNode the root) {
         int L = 0 ;
         int R & lt = 0 ;
         int max = 0 ;
         IF (the root == null ) {
             return 0 ; 
        }else {
            l = depth(root.left);
            r = depth(root.right);
            max = Math.max(l,r);
            return (max + 1);
        }
    }
}

 Bottom-up: In the process of seeking a depth, as long as there is a subtree condition is not satisfied, all the way -1

class Solution {
    public boolean isBalanced(TreeNode root) {
        return depth(root) == -1 ? false : true;
    }
    private int depth(TreeNode root) {
        if(root == null){
            return 0;
        }else{
            int l = depth(root.left);
            if(l==-1) return -1;
            int r = depth(root.right);
            if(r == -1) return -1;
            if(Math.abs(l-r) > 1) {
                return -1;
            }
            return Math.max(l,r) + 1;
        }
    }
}
View Code

 2, the binary tree diameter ( LeetCode title exam 543 )

Note that this problem is eye problems, the general said that the maximum value of casual working tree XX, XX is in the Child-giving tree

So this question is again begged the longest path to a node, as long as the longest path for each node of seeking out and taking the maximum you can;

Maximum path must generate left and right sides of the sub-tree, the required height of the tree.

This converted into two questions, seeking height of the tree, and find the longest path through each node

class Solution {
    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null) {
           return 0; 
        }else {
            int l = depth(root.left);
            int r = depth(root.right);
            int d = l + r;
            int dl = diameterOfBinaryTree(root.left);
            int dr = diameterOfBinaryTree(root.right);
            return Math.max(Math.max(d,dl),Math.max(dl,dr));
            
        }
    }
    private int depth(TreeNode root) {
        int l = 0;
        int r = 0;
        int max = 0;
        if(root == null) {
            return 0;
        }else {
            l = depth(root.left);
            r = depth(root.right);
            max = Math.max(l,r);
            return (max + 1);
        }
    }
}
View Code

3, the sum of path III ( LeetCode title exam 437 )

This problem is also thought to break down complex problems: we will seek a specific start point to any qualified end point of the path bar, then iterate over each point in the tree, not an arbitrary starting point is equivalent yet

class Solution {
     public  int pathSum (the root the TreeNode, int SUM) {
         IF (the root == null ) {
             return 0 ; 
        } the else {
             int COUNT = getPathFromRoot (the root, SUM); 
            COUNT = COUNT + pathSum (root.left, SUM) ; 
            COUNT = COUNT + pathSum (root.right, SUM);
             return COUNT; 
        } 
    } 
    // find the start to the end from the root node of any suitable route 
    Private  int getPathFromRoot (the TreeNode the root,int sum) {
        if(root == null) {
            return 0;
        }else {
            int count = 0;
            sum = sum - root.val;
            if(sum == 0 ) {
                count++;
            }
            count = count + getPathFromRoot(root.left,sum);
            count = count + getPathFromRoot(root.right,sum);
            return count;
        }
    }
}
View Code

4, sub-tree tree ( LeetCode 572 exam questions )

Decomposition idea: to write the first tree to determine whether the two codes are equal, traversing the tree again to see if there is no qualified sub-tree

class Solution {
    public boolean isSubtree(TreeNode s, TreeNode t) {
        if(s == null) {
           return false; 
        }else {
            if(isEquals(s,t)) {
                return true;
            }
            return isSubtree(s.left,t) || isSubtree(s.right,t);
        }
    }
    private boolean isEquals(TreeNode s, TreeNode t) {
        if(s == null || t == null) {
            if(s == null && t == null) {
                return true;
            }else {
                return false;
            }
        }else {
            if(s.val != t.val) {
                return false;
            }else {
                return isEquals(s.left,t.left) && isEquals(s.right,t.right);
            }
        }
    }
}
View Code

二、"||" 与 "&&"

This type of problem, is that the left and right subtrees have a satisfying returns true, it returns true or are met

1, the sum of the path ( LeetCode title exam 112 )

class Solution {
     // calculated sum values of each remaining node 
    public  Boolean hasPathSum (the root the TreeNode, int sum) {
         IF (the root == null ) {
             return  to false ; 
        } the else { 
            sum = sum - root.val;
             // equivalent in preorder traversal to find a leaf node and the remaining value is 0 
            IF (root.left == null && root.right == null && SUM == 0 ) {
                 return  to true ; 
            } 
            return hasPathSum (root.left, SUM) | |hasPathSum (root.right, SUM); 
        } 
    } 
    // Note that the return value is a recursive function bool type can not arbitrarily defined data type int 
}

 2, the tree subtree (572 questions) with the above

Third, the control condition

Such practice in the control of these conditions are a little difficult.

1, merging binary tree ( LeetCode 617 exam questions )

class Solution {
    public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if(t1 == null || t2 == null) {
            return t1 == null ? t2 : t1;
        }else {
            t1.val = t1.val + t2.val;
            t1.left = mergeTrees(t1.left,t2.left);
            t1.right = mergeTrees(t1.right,t2.right);
            return t1;
        }
    }
}

 2, the minimum depth of the tree ( LeetCode title exam 111 )

class Solution {
    public int minDepth(TreeNode root) {
        if(root == null) {
            return 0;
        }else {
            int l = 0;
            int r = 0;
            l = minDepth(root.left);
            r = minDepth(root.right);
            if(root.left == null || root.right == null)
                return l + r + 1;
            else
                return Math.min(l,r) + 1;
        }
    }
}
View Code

 Fourth, transform ideas

1, the left and leaves ( LeetCode 404 exam questions )

Due to judge the "left" So the need for a parent pointers, recursion is no way to use the parent pointer, so the thought of non-recursive tree traversal

Method a: Non-recursive methods

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
         if(root == null) {
            return 0;
        }else {
            Stack<TreeNode> stack = new Stack<>();
            TreeNode p = root;
            int sum = 0;
            while(!stack.isEmpty() || p != null) {
                while(p != null) {
                    stack.push(p);
                    p = p.left;
                }
                if(!stack.isEmpty()) {
                    p = stack.pop();
                    if(p.left==null&&p.right==null) {
                        if(!stack.isEmpty()) {
                            if(stack.peek().left==p) 
                                sum = sum + p.val;
                        }
                    }
                    p = p.right;
                }
            }
            return sum;
        }
    }
}
View Code

 

Method two: recursion

Although recursion can not give us the parent pointer, but we can change my thinking, the problems into the left child node judgment is not a leaf node

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if(root == null) {
           return 0; 
        }else {
            int sum = 0;
            if(isLeaf(root.left)) {
                sum = sum + root.left.val;
            }else {
                sum = sum + sumOfLeftLeaves(root.left);
            }
            sum = sum + sumOfLeftLeaves(root.right);
            return sum;
        }
    }
    boolean isLeaf(TreeNode leaf) {
        if(leaf == null) return false;
        else if(leaf.left == null && leaf.right == null)
            return true;
        else
            return false;
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/mgblogs/p/11655126.html