Data structure java version of binary tree (part of the offer interview questions)

 Don't look at my leopard! look down! ! !

content

First, the basic operation of binary tree

1. Get the number of nodes in the tree

2. Get the number of leaf nodes

3. Sub-problem idea - find the number of leaf nodes

4. Get the number of nodes in the Kth layer

5. Get the height of the binary tree

6. Check if the element whose value is value exists

7. Determine whether a tree is a complete binary tree

Two, binary tree related oj questions

1. Check if two trees are the same

2. A subtree of another tree

3. Maximum depth of binary tree

4. Determine whether a binary tree is a balanced binary tree

5. Symmetric Binary Tree

6. Construction and traversal of binary tree

7. Hierarchical traversal of binary tree

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

9. Convert binary tree search tree into sorted doubly linked list

10. Construct a binary tree based on preorder traversal and inorder traversal of a tree

11. Construct a binary tree based on in-order traversal and post-order traversal of a tree

12. Binary tree to create string

13. Binary tree preorder non-recursive traversal implementation

14. Inorder non-recursive traversal implementation of binary tree


First, the basic operation of binary tree

1. Get the number of nodes in the tree

Two ways of thinking:

① Traversing the idea:

   Define a counter count, traverse the binary tree, count++ if there are nodes; (the traversal method here can be any of the pre-middle-post-order traversal written in the blog in the previous chapter)

The code is as follows: ! ! ! Note that count needs to be defined outside this function, otherwise its count value will return to the initializer when recursing

 int count=0;
    //以遍历的思路写
    int size1(BTNode root){
        if(root==null) {
            return 0;
        }else{
            count++;
             size1(root.left);
             size1(root.right);
        }
        return count;
    }

②Sub-question ideas:

 code show as below:

    //以子问题思路写
    int size(BTNode root){
        if(root==null){
            return 0;
        }
       return  size(root.left)+size(root.right)+1;
    }

2. Get the number of leaf nodes

Two ways of thinking:

① Traversal implementation:

Code:

//以遍历的方式访问
    int count1=0;
    int getLeafNodeCount(BTNode root){
       // int count1=0;
        if(root==null){
            return 0;
        }else if(root.left==null && root.right==null){
            count1++;
        }
        getLeafNodeCount(root.left);
        getLeafNodeCount(root.right);
        return count1;
    }

②Sub-question ideas:

code show as below:

int getLeafNodeCount(BTNode root){
        if(root==null){
            return 0;
        }else if(root.left==null && root.right==null){
            return 1;
        }
        return getLeafNodeCount(root.left)+getLeafNodeCount(root.right);
    }
}

3. Sub-problem idea - find the number of leaf nodes

     This question has been obtained in the second idea in 2

4. Get the number of nodes in the Kth layer

 Problem solving ideas:

code show as below:

//求第K层结点的个数
 public int getKLevelNodeCount(int k){
    return getKLevelNodeCount(root, k);
    }
     // 获取第K层结点的个数
    private int getKLevelNodeCount(BTNode root,int k){
          if(root==null || k<=0){
             return 0;
          }
          if(k==1){
              return 1;
          }
          return getKLevelNodeCount(root.left, k-1)+getKLevelNodeCount(root.right, k-1);

    }

5. Get the height of the binary tree

Thought analysis:

code show as below:

 // 获取二叉树的高度(时间复杂度为O(n))
    int getHeight(BTNode root){
        if(root==null){
            return 0;
        }
       int leftHeight=getHeight(root.left);
        int rightHeight=getHeight(root.right);
//此处用的是三目运算符求取两者中的较大值
        return leftHeight>rightHeight?leftHeight+1:rightHeight+1;
    }

6. Check if the element whose value is value exists

Problem solving ideas:

code show as below:

// 检测值为value的元素是否存在
    boolean find(BTNode root, int val) {
        if (root == null) {
            return false;
        } else if (root.val == val) {
            return true;
        }
        if (find(root.left, val) || find(root.right, val)) {
            return true;
        }
        return false;
    }

7. Determine whether a tree is a complete binary tree

Problem solving ideas:

code show as below:

  boolean isCompleteTree(BTNode root){
        if(root == null) return true;
        Queue<BTNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            BTNode cur = queue.poll();
            if(cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            }else {
                break;
            }
        }
//第二个while循环实质上就是在cur=null的基础上来判断实现的,若是整个为空即null 则true;反之为false
        while (!queue.isEmpty()) {
            BTNode top = queue.peek();
            if(top != null) {
                return false;
            }
            queue.poll();
        }
        return true;
    }

1. Check if two trees are the same

100. The same tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/same-tree/

Problem solving ideas:

   To tell if two trees are the same: 

   ①The structure of numbers is the same

   ②The value corresponding to the node at the corresponding position is the same

code show as below:

 public boolean isSameTree(TreeNode p, TreeNode q ){
        if(p == null && q != null || p != null && q == null) {
            return false;
        }
        if(p == null && q == null) {
            return true;
        }
        if(p.val != q.val) {
            return false;
        }
        //p != null && q!= null && p.val == q.val
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }

2. A subtree of another tree

572. Subtree of Another Tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/subtree-of-another-tree/

code show as below:

 public boolean isSubtree(TreeNode root, TreeNode subRoot) {
  if(root == null || subRoot == null) {
             return false;
         }
        //根节点和subroot是不是两颗相同的树
        if(isSameTree(root,subRoot)) {
            return true;
        }
        //subRoot是不是root的左子树
        if(isSubtree(root.left,subRoot)) {
            return true;
        }
        if(isSubtree(root.right,subRoot)) {
            return true;
        }
        return false;
}
}

3. Maximum depth of binary tree

104. Maximum depth of binary tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

 5 questions about the basic operation of the same binary tree, please refer to the top of this blog

4. Determine whether a binary tree is a balanced binary tree

110. Balanced Binary Tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/balanced-binary-tree/submissions/

Problem solving ideas: 

class Solution {
   public int height (TreeNode root) {
        if(root == null) {return 0;}
        int leftHeight = height(root.left);
        int rightHeight = height(root.right);
        return (leftHeight > rightHeight) ?
                (leftHeight+1) :(rightHeight+1);
    }

    /**
     时间复杂度:O(N^2)
     */
    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        int left = height(root.left);
        int right = height(root.right);
        return Math.abs(left-right) <= 1 && isBalanced(root.left) && isBalanced(root.right);
    }
}

5. Symmetric Binary Tree

101. Symmetric Binary Tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/symmetric-tree/Solution ideas:

code show as below:

class Solution {
     public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return isSymmetricChild(root.left,root.right);
    }
   public boolean isSymmetricChild(TreeNode leftTree,TreeNode rightTree) {
       //第一种情况
       if(leftTree == null && rightTree == null) return true;
       //第二种情况
        if((leftTree == null && rightTree != null)||(leftTree != null && rightTree == null))               return false;
        //第三种情况
        if(leftTree.val != rightTree.val) return false;
        return isSymmetricChild(leftTree.left,rightTree.right) &&
                isSymmetricChild(leftTree.right,rightTree.left);
    }

6. Binary tree construction and traversalicon-default.png?t=M0H8

7. Hierarchical traversal of binary tree

102. Level-order traversal of binary tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

Problem solving ideas:

print hierarchical traversal with the help of a queue and a temporary variable cur

① Discuss the case of whether the root is empty or not

②When the queue is not empty, dequeue the tail element in the queue to cur, and print it through cur.val

③The situation of the left and right subtrees is discussed in a loop, so use while to loop

Two types of codes:

①Common code:

  //打印层序遍历二叉树
  public void levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
//①判断树是否为空的情况
        if(root == null) return;
        queue.offer(root);
//②判断队列是否为空
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val+" ");
            if(cur.left != null) {
                queue.offer(cur.left);
            }
            if(cur.right != null) {
                queue.offer(cur.right);
            }
        }
    }

②The code for solving the problem on OJ:

Problem solving ideas: 

code show as below:

//层序遍历访问打印元素
List<List<Integer>> ret = new ArrayList<>();
        if(root == null) return ret;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
//当前的结点个数size
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while (size != 0) {
                TreeNode cur = queue.poll();
//将同层结点放在一个list中
                list.add(cur.val); 
                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
                size--;//1 0
            }
//将所有一层link的结点放在同一个list中
            ret.add(list);
        }
//最后返回整个所需的ret
        return ret;
}

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

236. The nearest common ancestor of binary tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/

Problem solving ideas:

Idea 1 : A method of designing a binary tree from the idea of ​​a binary search tree

If a binary search tree

Detailed ideas:

1. root==p || root==q (p, q is a node)
The nearest common ancestor at this time is root
2. It may be on the left or right of the root
① p.val<root.val && q.val< root.val (p, q are both in the left subtree of root) the
nearest common ancestor is in the left subtree


②p.val>root.val && q.val>root.val (p, q are both in the right subtree of root)
The nearest common ancestor is in the right subtree


3. The nearest common ancestor is root
①p.val>root.val && q.val<root.val (p is in the left subtree, q is in the right subtree)
②p.val<root.val && q.val> root.val (p is in the right subtree, q is in the left subtree)


 code show as below:

//二叉树的最近公共祖先
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return null;
        }if(root==p||root==q){
            return root;
        }
        TreeNode l=lowestCommonAncestor(root.left,p,q);
        TreeNode r=lowestCommonAncestor(root.right,p,q);
       if(l!=null && r!=null){
    return root;
}else if(l!=null){
    return l;
}else{
    return r;
}
        }
    }

 Thought ② :

Obtained from the parental representation of the child 

code show as below:

class Solution {
    //root:
    public boolean getPath(TreeNode root,TreeNode node,Stack<TreeNode>stack){
if(root==null || node==null){
return false;
}stack.push(root);
if(root==node){
    return true;
}
boolean flg=getPath(root.left,node,stack);
if(flg==true){
    return true;
}
 flg=getPath(root.right,node,stack);
 if(flg==true){
     return true;
 }
stack.pop();
return false;
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null){
            return null;
        }
        Stack<TreeNode> stack1=new Stack<>();
        getPath(root,p,stack1);
        Stack<TreeNode> stack2=new Stack<>();
        getPath(root,q,stack2);
        int size1=stack1.size();
        int size2=stack2.size();
        if(size1>size2){
            int size=size1-size2;
            while(size!=0){
            stack1.pop();
            size--;
            }
            while(!stack1.isEmpty() && !stack2.isEmpty()){
                //用等号判断地址
                if(stack1.peek()==stack2.peek()){
                    return stack1.pop();
                }else{
                    stack1.pop();
                    stack2.pop();
                }
            }
            }else{
                 int size=size2-size1;
            while(size!=0){
            stack2.pop();
            size--;
            }
            while(!stack1.isEmpty() && !stack2.isEmpty()){
                //用等号判断地址
                if(stack1.peek()==stack2.peek()){
                    return stack1.pop();
                }else{
                    stack1.pop();
                    stack2.pop();
                }
            }
            }
            return null;
        }
    }

9. Convert binary tree search tree into sorted doubly linked list

Niuke.com link https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5?tpId=13&&tqId=11179&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking problem- solving ideas:

The characteristics of the binary search tree have been introduced before (so it is known that the binary search tree is ordered when traversed in order)

①Inorder traversal of this binary tree

② Doubly linked list

 code show as below:

public class Solution {
    //先写出一个中序遍历
    TreeNode prev=null;
    public void inOrder(TreeNode pCur){
        if(pCur==null)return ;
        inOrder(pCur.left);
        pCur.left=prev;
        if(prev!=null){
              prev.right=pCur;
        }
      prev=pCur;
          inOrder(pCur.right);
    }
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree==null){
            return null;
        }
        inOrder(pRootOfTree);
        TreeNode head=pRootOfTree;
        while(head.left!=null){
            head=head.left;
        }
        return head;
    }
}

10. Construct a binary tree based on preorder traversal and inorder traversal of a tree

105. Construct binary tree from preorder and inorder traversal sequence - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder- traversal/

Problem solving ideas:

①Find the root node

② Find the left and right subtrees through in-order traversal

③ Create left and right subtrees respectively

code show as below:

class Solution {
//将preIndex设置为全局变量用来保证在递归的过程中当子树根结点返回到总根后的空指针异常
    public int preIndex=0;
    public TreeNode createTreeByPandI(int[]preorder,int[]inorder,int inbegin,int inend){
        if(inbegin>inend){
            //左树或者右树为空
            return null;
        }
        TreeNode root=new TreeNode(preorder[preIndex]);
        int rootIndex=findIndexOfI(inorder,inbegin,inend,preorder[preIndex]);
            if(rootIndex==-1){
                return null;
            }
            preIndex++;
            root.left=createTreeByPandI(preorder,inorder,inbegin,rootIndex-1);
            root.right=createTreeByPandI(preorder,inorder,rootIndex+1,inend);
            return root;
        }
    private int findIndexOfI(int[]inorder,int inbegin,int inend,int key){
        for(int i=inbegin;i<=inend;i++){
            if(inorder[i]==key){
                return i;
            }
        }
return -1;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder==null||inorder==null){
    return null;
}return createTreeByPandI(preorder,inorder,0,inorder.length-1);
    }
}

11. Construct a binary tree based on in-order traversal and post-order traversal of a tree

106. Construct binary tree from inorder and postorder traversal sequence - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder- traversal/ problem- solving ideas:

Differences from the previous question:

①postIndex is on the far right (that is, if the root node is traversed in post-order, it will be traversed forward one after another)

② Visit the right tree first and then the left tree

code show as below:

class Solution {
 public int postIndex=0;
    public TreeNode createTreeByPandI(int[]inorder,int[]postorder,int inbegin,int inend){
        if(inbegin>inend){
            //左树或者右树为空
            return null;
        }
        TreeNode root=new TreeNode(postorder[postIndex]);
        int rootIndex=findIndexOfI(inorder,inbegin,inend,postorder[postIndex]);
            if(rootIndex==-1){
                return null;
            }
            postIndex--;
            //分别创建右子树和左子树
            root.right=createTreeByPandI(inorder,postorder,rootIndex+1,inend);
            root.left=createTreeByPandI(inorder,postorder,inbegin,rootIndex-1);
            return root;
        }
    private int findIndexOfI(int[]inorder,int inbegin,int inend,int key){
        for(int i=inbegin;i<=inend;i++){
            if(inorder[i]==key){
                return i;
            }
        }
return -1;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        postIndex=postorder.length-1;
if(postorder==null||inorder==null){
    return null;
}return createTreeByPandI(inorder,postorder,0,inorder.length-1);
    }
}

 12. Binary tree to create string

606. Create a String Based on Binary Tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/construct-string-from-binary-tree/Problem-solving
ideas:

 code show as below:

class Solution {
  public void treeToString(TreeNode t,StringBuilder sb) {
        if(t == null) return;
        sb.append(t.val);
        if(t.left != null) {
            sb.append("(");
            treeToString(t.left,sb);
            sb.append(")");
        }else {
            //t.left == null
            if(t.right == null) {
                return;
            }else{
                sb.append("()");
            }
        }

        if(t.right == null) {
            return;
        }else{
            sb.append("(");
            treeToString(t.right,sb);
            sb.append(")");
        }
    }
    public String tree2str(TreeNode root) {
        if(root == null) return null;
        StringBuilder sb = new StringBuilder();
        treeToString(root,sb);
        return sb.toString();
    }
}

13. Binary tree preorder non-recursive traversal implementation

144. Preorder Traversal of Binary Tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/binary-tree-preorder-traversal/submissions/

Problem solving ideas:

code show as below:

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer>ret=new ArrayList<>();
        Stack<TreeNode>stack=new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            System.out.print(top.val+" ");
            cur = top.right;
        }
        return ret;
    }

14. Inorder non-recursive traversal implementation of binary tree

94. Inorder Traversal of Binary Tree - LeetCode (leetcode-cn.com) https://leetcode-cn.com/problems/binary-tree-inorder-traversal/

Problem-solving idea: the same preorder non-recursive traversal implementation of 13

code show as below:

class Solution {
 public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> ret= new ArrayList<>();
            Stack<TreeNode> stack = new Stack<>();
            TreeNode cur = root;
            while (cur != null || !stack.isEmpty()) {
                if (cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                } else {
                    cur = stack.pop();
                    ret.add(cur.val);
                    cur = cur.right;
                }
            }
            return ret;
        }
    }

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/122564501