zoukankan      html  css  js  c++  java
  • 算法:二叉查找树进阶

    算法:二叉查找树进阶

    LeetCode—Two Sum IV - Input is a BST

    问题描述

      给定一个二叉搜索树和一个目标编号,如果BST中存在两个元素,若它们的和等于给定值,则返回true。

    Example 1:

      Input: 
          5
         / 
        3   6
       /    
      2   4   7
    
      Target = 9
      Output: True

    Java代码

    class Solution {
        ArrayList<Integer> ints = null;
        public boolean findTarget(TreeNode root, int k) {
            ints = new ArrayList<>();
            preTraverse(root);
            
            int i =ints.size()-1;
            int j = 0;
    
        //在排序好的列表中找到两个和为目标值的序号
            while (j<i)
            {
    
                int sum = ints.get(i)+ints.get(j);
                if(sum==k)
                    return true;
                if(sum<k)
                    j++;
                else
                    i--;
            }
            return false;
        }
      //中序遍历,可以将二叉树从小到达排列出来!
        public void preTraverse(TreeNode T)
        {
            if(T!=null)
            {
    
                preTraverse(T.left);
                ints.add(T.val);
                preTraverse(T.right);
            }
        }
    }

    解题思考

    1.使用广度优先搜索和HashSet求解

    public class Solution {
        public boolean findTarget(TreeNode root, int k) {
            Set < Integer > set = new HashSet();
            Queue < TreeNode > queue = new LinkedList();
            queue.add(root);
            while (!queue.isEmpty()) {
                if (queue.peek() != null) {
                    TreeNode node = queue.remove();
                    if (set.contains(k - node.val))
                        return true;
                    set.add(node.val);
                    queue.add(node.right);
                    queue.add(node.left);
                } else
                    queue.remove();
            }
            return false;
        }
    }
    

      

    LeetCode—Construct String from Binary Tree 

     问题描述

    You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

    The null node needs to be represented by empty parenthesis pair "()". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.

    Example 1:

    Input: Binary tree: [1,2,3,4]
           1
         /   
        2     3
       /    
      4     
    
    Output: "1(2(4))(3)"
    
    Explanation: Originallay it needs to be "1(2(4)())(3()())",
    but you need to omit all the unnecessary empty parenthesis pairs.
    And it will be "1(2(4))(3)".

    Java代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        StringBuilder sb = new StringBuilder();
        public String tree2str(TreeNode t) {
            preTraverse(t);
            String re = sb.toString();
         //处理子元素为空的情况,即(5()()) ——>(5) re = re.replaceAll("\(\)\(\)","");
         //处理第二个子元素为空的情况,即(5(1)())——>(5(1)) re = re.replaceAll("\)\(\)",")"); return re.substring(1,re.length()-1); } //这里是先序遍历 public void preTraverse(TreeNode T) { if(T!=null) { sb.append("("); sb.append(T.val); preTraverse(T.left); preTraverse(T.right); sb.append(")"); }else { sb.append("()"); } } }
  • 相关阅读:
    mysql(自动添加系统时间)timestamp类型字段的CURRENT_TIMESTAMP与ON UPDATE CURRENT_TIMESTAMP属性
    五分钟带你了解啥是JWT
    Eureka和ZooKeeper的区别
    SpringCloud系列之: Eureka注册中心原理及其搭建
    总结下微服务中降级、熔断,以及springcloud中Hystrix的原理以及实现
    POJ1113:Wall (凸包算法学习)
    Java-Graphics类的绘图方法实现
    java.awt.event.MouseEvent鼠标事件的定义和使用 以及 Java Swing-JTextArea的使用
    java swing JDialog 和 java.util.concurrent的使用
    Java-Swing的JFrame的一些插件使用详解
  • 原文地址:https://www.cnblogs.com/MrSaver/p/8446520.html
Copyright © 2011-2022 走看看