The pre-order traversal and post-order traversal of the binary tree (the variant of the question type is being updated)

Metamorphosis one

BM32 merge binary tree

describe

Given two binary trees, merge them into one binary tree. The merging rule is: if there are all nodes, the node values ​​will be added, otherwise the empty position will be replaced by another tree node. For example:
two binary trees are:
                                                                    Tree 1



                                                                        Tree 2



                                                                    The merged tree is

Data range: The number of nodes on the tree satisfies 0≤n≤500, and the value of the nodes on the tree must be within the range of 32-bit integers.

Advanced: space complexity O(1), time complexity O(n)

Example 1

enter:

{1,3,2,5},{2,1,3,#,4,#,7}

return value:

{3,4,5,5,4,#,7} 

Example 2

enter:

{1},{}

return value:

{1}

preorder traversal

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param t1 TreeNode类 
     * @param t2 TreeNode类 
     * @return TreeNode类
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        if(t1==null)
            return t2;
        if(t2==null)
            return t1;
        t1.val+=t2.val;
        t1.left=mergeTrees(t1.left,t2.left);
        t1.right=mergeTrees(t1.right,t2.right);
        return t1; 
    }
}

 

Metamorphosis two

Mirror image of BM33 binary tree

describe

Operates on the given binary tree, transforming it into a mirror image of the source binary tree.

Data range: the number of nodes of the binary tree 0≤n≤1000, the value of each node of the binary tree 0≤val≤1000

Requirements: Space complexity O(n). This question also has an in-place operation, that is, a solution with space complexity O(1) and time complexity O(n)

for example:

source binary tree

mirrored binary tree

Example 1

enter:

{8,6,10,5,7,9,11}

return value:

{8,10,6,11,9,7,5}    

Example 2

enter:

{}

return value:

{}

Problem-solving steps:

1. Special judgment: if pRoot is empty, return empty

2. Swap the left and right subtrees
3. Put the left subtree of pRoot in the Mirror for mirroring
4. Put the right subtree of pRoot in the Mirror for mirroring
5. Return to the root node root

preorder and postorder traversal

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param pRoot TreeNode类 
     * @return TreeNode类
     */
    public TreeNode Mirror (TreeNode pRoot) {
        // write code here
        if(pRoot==null){
            return pRoot;
        }
//         //后序遍历
//         TreeNode left=Mirror(pRoot.left);  //递归左子树
//         TreeNode right=Mirror(pRoot.right);  //递归右子树
//         //左右子树交换    
//         pRoot.left=right;
//         pRoot.right=left;
        
        //前序遍历也可以
        TreeNode temp=pRoot.left;
        pRoot.left=pRoot.right;
        pRoot.right=temp;
        
        pRoot.left=Mirror(pRoot.left);
        pRoot.right=Mirror(pRoot.right);
        
        return pRoot;
    }
}

Metamorphosis three 

BM36 judge whether it is a balanced binary tree

describe

Input a binary tree with n nodes, and judge whether the binary tree is a balanced binary tree.

Here, we only need to consider its balance, not whether it is a sorted binary tree

A balanced binary tree has the following properties: it is an empty tree or the absolute value of the height difference between its left and right subtrees does not exceed 1, and both left and right subtrees are a balanced binary tree.

Example explanation:

The sample binary tree is shown in the figure, which is a balanced binary tree

Note: We agree that an empty tree is a balanced binary tree.

Data range: 0n≤100, the val value of the node on the tree satisfies 0≤n≤1000

Requirements: space complexity O(1), time complexity O(n)

Enter a description:

Enter the root node of a binary tree

Return value description:

output a boolean value

Example 1

enter:

{1,2,3,4,5,6,7}

return value:

true

Example 2

enter:

{}

return value:

true

Solution: (post-order traversal)

A template for finding the height of a binary tree

public class Solution {
  
    boolean isb=true;  //标记是否是平衡二叉树
    public int dfs(TreeNode root){
        if(root==null){
            return 0;
        }
        //自底向上,先求左右子树高度
        int l=dfs(root.left);
        
        int r=dfs(root.right);
        
        if(Math.abs(l-r)>1){  //(左子树深度-右子树深度) > 1,不是平衡树
            isb=false;
        }
        
        return Math.max(l,r)+1;  //求深度
    }
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null){
            return true;
        }
         dfs(root);
         return isb;    
    }
}

The above code always traverses all the nodes. If it is judged that the difference between the depths of the left and right subtrees is greater than 1, the binary tree cannot be a balanced tree anymore. Therefore, we can also optimize the above code.

Pruning : When it is judged that the difference between the depths of the left and right subtrees is greater than 1, return -1. At the end of each recursion, judge whether the return value is -1, and if it is -1, return immediately.

So the optimized code is:

public class Solution {  
    boolean isb=true;
    public int dfs(TreeNode root){
        if(root==null){
            return 0;
        }
        //自底向上,先求左右子树高度
        int l=dfs(root.left);
        if(l==-1){  //如果左子树已经不是平衡二叉树,则返回-1,不需要再去访问右子树了
            return -1;
        }
        int r=dfs(root.right);
        if(r==-1){  //如果右子树已经不是平衡二叉树,则返回-1,不需要再去访问递归了
            return -1;
        }
        if(Math.abs(l-r)>1){  //(左子树深度-右子树深度) > 1,不是平衡树
            isb=false;
            return -1;  //提前结束,避免遍历所有的节点
        }
        
        return Math.max(l,r)+1;  //求深度
    }
    public boolean IsBalanced_Solution(TreeNode root) {
        if(root==null){
            return true;
        }

        int len=dfs(root);
        if(len==-1){
            return false;
        }
        else{
            return true;
        }
            
    }
}

Metamorphosis four

BM37 The nearest common ancestor of a binary search tree

describe

Given a binary search tree, find the nearest common ancestor of two specified nodes in the tree.

1. The definition of the nearest common ancestor for this question: For two nodes p and q of a rooted tree T, the nearest common ancestor LCA(T, p, q) represents a node x, satisfying that x is the ancestor of p and q and The depth of x is as large as possible. Here, a node can also be its own ancestor.

2. A binary search tree is that if its left subtree is not empty, the values ​​of all nodes on the left subtree are less than the value of its root node; if its right subtree is not empty, all nodes on the right subtree The value of is greater than the value of its root node

3. The values ​​of all nodes are unique.

4. p, q are different nodes and both exist in a given binary search tree.

data range:

3<=total number of nodes<=10000

0<=node value<=10000

If given the following search binary tree: {7,1,12,0,4,11,14,#,#,3,5}, as shown below:

 code:

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */

    public int lowestCommonAncestor (TreeNode root, int p, int q) {
        // write code here
       //避免了判断p,q值那个大
        if((p-root.val)*(q-root.val)<=0){  //两个节点值在root左右两边
            return root.val;
        }
        else if(p>root.val&&q>root.val){
            return lowestCommonAncestor(root.right,p,q);
        }else{
            return lowestCommonAncestor(root.left,p,q);
        }
     }
            
}

Variation 5 (general binary tree to find the nearest common node) (pre-order traversal)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @param p int整型 
     * @param q int整型 
     * @return int整型
     */

    public int lowestCommonAncestor (TreeNode root, int p, int q) { 
        //一般二叉树
        if(root==null){  //没有找到p或者q
            return -1;  //返回-1
        }
        //前序遍历:根左右
        if(root.val==p||root.val==q){  //如果遍历到其中一个节点,则该节点就是两个节点最近祖先
           return root.val;    //两个节点的祖先
        }
        int l=lowestCommonAncestor(root.left,p,q);
        int r=lowestCommonAncestor(root.right,p,q);
        if(l==-1){  //如果左子树中没有两个节点p,q,则说明两个节点都在右子树上
            return r;    //返回右子树第一个遇到的节点,就是最近公共祖先
        }
        if(r==-1){ //如果右子树中没有两个节点p,q,则说明两个节点都在左子树上
           return l;   // 返回右子树第一个遇到的节点,就是最近公共祖先
        }
        return root.val;    //如果左右子树各有一个节点值,则他们的最近公共节点是root.val
     }
}

Guess you like

Origin blog.csdn.net/hgnuxc_1993/article/details/123733493