1、二叉树的最近公共祖先

例如,给定如下二叉树:  root = [3,5,1,6,2,0,8,null,null,7,4]

 

示例 1:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
输出: 3
解释: 节点 5 和节点 1 的最近公共祖先是节点 3。

示例 2:

输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
输出: 5
解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。

说明:

  • 所有节点的值都是唯一的。
  • p、q 为不同节点且均存在于给定的二叉树中。

代码如下:

  • 递归实现

class Solution {
    private TreeNode ans;
    public Solution(){
        ans = null;
    }
    private boolean recurseTree(TreeNode curNode, TreeNode p, TreeNode q){
        if(curNode == null) return false;
        int left = this.recurseTree(curNode.left, p, q)?1:0;
        int right =this.recurseTree(curNode.right, p, q)?1:0;
        int mid = (curNode == p || curNode == q)?1:0;
        if(left+right+mid>=2) this.ans = curNode;
        return (left+right+mid > 0);
    }
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        this.recurseTree(root, p, q);
        return this.ans;
    }
}

非递归实现:

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        Deque<TreeNode> stack = new ArrayDeque<>();

        Map<TreeNode, TreeNode> parent = new HashMap<>();

        

        parent.put(root, null);

        stack.push(root);

        

        while(!parent.containsKey(p) || !parent.containsKey(q)){

            TreeNode node = stack.pop();

            

            if(node.left!=null){

                parent.put(node.left, node);

                stack.push(node.left);

            }

            

            if(node.right!=null){

                parent.put(node.right, node);

                stack.push(node.right);

            }

        }

        

        Set<TreeNode> ancestor = new HashSet<>();

        while(p!=null){

            ancestor.add(p);

            p = parent.get(p);

        }

        while(!ancestor.contains(q)){

            q= parent.get(q);

        }

        return q;

    }

2、判断一个字符串是否是一个IPV4。

public class IPV4{

          public static final String DELIM = "\\.";

          private boolean isValidIP(String ip){

                      if(ip==null || "".equals(ip.trim())){

                                 return false;

                      }

                      String[] parts = ip.split(DELIM);

                      if(parts.length!=4){

                                   return false;

                      }

                      for(String part: parts){

                                    try{

                                                  int intVal = Integer.parseInt(part);

                                                  if(intVal < 0 || intVal > 255) return false;

                                        }catch(NumberFormatException e){

                                                  return false;

                                        }

                      }

                      return true;

         }

}