zoukankan      html  css  js  c++  java
  • 993. 二叉树的堂兄弟节点

    这题的难点在于怎么判断查询到的2个节点没有同一个父节点,因此我们每次遍历的

    时候,就记录下当前节点的左右子节点,然后对下一层做判断,这样每一层遍历的时候

    就能得出下一层的结果

    时间O(n),空间O(n)

     1 public boolean isCousins(TreeNode root, int x, int y) {
     2         Deque<TreeNode> queue = new LinkedList<TreeNode>();
     3         queue.add(root);
     4         while(!queue.isEmpty()){
     5             int size=queue.size();
     6             boolean flag1 = false;
     7             boolean flag2 = false;
     8             TreeNode p1 = null;
     9             TreeNode p2 = null;
    10             while(size-->0){
    11                 TreeNode temp = queue.poll();
    12                 if(temp.left!=null){
    13                     queue.add(temp.left);
    14                     if(temp.left.val==x){
    15                         flag1=true;
    16                         p1=temp;
    17                     }
    18                     if(temp.left.val==y){
    19                         flag2=true;
    20                         p2=temp;
    21                     }
    22                 }
    23                 if(temp.right!=null){
    24                     queue.add(temp.right);
    25                     if(temp.right.val==x){
    26                         flag1=true;
    27                         p1=temp;
    28                     }
    29                     if(temp.right.val==y){
    30                         flag2=true;
    31                         p2=temp;
    32                     }
    33                 }
    34             }
    35             // 存在x和y的情况下,需要确认这两个节点不在同一个父节点下
    36             if(flag1 && flag2){
    37                 return p1!=p2;
    38             }
    39         }
    40         return false;
    41     }
    争取早日不再是一只菜鸡
  • 相关阅读:
    vmware fusion和mac共享目录
    安卓linker源码阅读01
    sublime text 快捷键
    eclipse使用经验汇总
    递归池:
    ubuntu下adb红米
    蛋疼问题汇总you must restart adb and eclipse
    JNI
    ARM寻址
    了解装饰器
  • 原文地址:https://www.cnblogs.com/jchen104/p/14767767.html
Copyright © 2011-2022 走看看