二叉树的几个问题

1、层次遍历

public static  ArrayList cengci(TreeNode root){

     ArrayDeque queue = new ArrayDeque();

     queue.add(root);

   ArrayList result = new ArrayList();

    while(queue.size()!= 0){

 ArrayList single = new ArrayList();

          int size. = queue.size();

          for(int i = 0;i

             TreeNode temp = queue.pop();

              single.add(temp);

             if(temp.left != null){

            queue.add(temp.left);

              }

if(temp.right != null){

            queue.add(temp.right);

              }

          }

     result.add(single);

     }

return result;

}


2、交换左右节点

public static TreeNode jiaohuan(TreeNode root)){

           if (root === null){

return  null;

         }

       TreeNode left = jiaohuan(root.left);

        TreeNode right = jiaohuan(root.right);

         root.left = right;

         root.right = left;

        return root;

}

3、二叉树最大深度

public static int maxdep(TreeNode root){

       if(root == null){

          return 0;

        } 

       int left = maxdep(root.left);

       int right =  maxdep(root.right);

      return Math.max(left,right) +1;

}

4、某个路径和等于指定target

public static ArrayList result = new ArrayList();

public static ArrayList targersum(TreeNode root,int target){

       back(root,target,new ArrayList);

       return result;

}

public static void back(TreeNode root,int target,ArrayList path){

if (root == null){

              return ;

          }

         path.add(root.val);

         target = target - root.val;

         if(target == 0 && root.left == null && root.right == null){

                    result.add(new ArrayList(path));

          }

         back(root.left,target,path);

         back(root.right,target,path);

         path.remove(path.size()-1);

}

5、二叉搜索树的公共祖先

public static TreeNode zuxian(TreeNode root ,TreeNode s1, TreeNode s2,){

if (root.val >=s2.val && root.val <=s1.val){

             return root;

       }

        if(root.val >s2.val && root.val>s1.val){

               return zuxian(root.right, s1,s2);

          }else{

return zuxian(root.left, s1,s2);

            }

}

6、二叉树公共祖先

public static TreeNode zuxian(TreeNode root ,TreeNode s1, TreeNode s2,){

if (root == null || s1.val == root.val || s2.val == root.val){

             return root;

           }

      TreeNode left = zuxian(root.left,s1,s2);

       TreeNode right = zuxian(root.right,s1,s2);

       if (left != null && right != null){

         return root;

        }

       return left ?right == null :right;


}

你可能感兴趣的:(二叉树的几个问题)