zoukankan      html  css  js  c++  java
  • 剑指offer-对称的二叉树

    题目描述:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

    ac代码:

     1 /*
     2 public class TreeNode {
     3     int val = 0;
     4     TreeNode left = null;
     5     TreeNode right = null;
     6 
     7     public TreeNode(int val) {
     8         this.val = val;
     9 
    10     }
    11 
    12 }
    13 */
    14 import java.util.ArrayList;
    15 public class Solution {
    16     boolean isSymmetrical(TreeNode pRoot)
    17     {
    18          dfs1(pRoot,1);
    19         Mirror(pRoot);
    20         dfs2(pRoot,1);
    21         if(list1.size()!=list2.size())
    22             return false;
    23         for(int i=0;i<list1.size();i++){
    24             if(list1.get(i)!=list2.get(i)){
    25                 return false;
    26             }
    27         }
    28         return true;
    29     }
    30       ArrayList<Integer>list1=new ArrayList<Integer>();
    31      ArrayList<Integer>list2=new ArrayList<Integer>();
    32     void dfs1(TreeNode p,int t){
    33         if(p!=null){
    34             if(t==1)
    35             list1.add(p.val+1);
    36             if(t==2)
    37             list1.add(p.val+2);
    38             dfs1(p.left,1);
    39             dfs1(p.right,2);
    40         }
    41     }
    42     void dfs2(TreeNode p,int t){
    43         if(p!=null){
    44             if(t==1)
    45                 list2.add(p.val+1);
    46                 if(t==2)
    47                 list2.add(p.val+2);
    48                 dfs2(p.left,1);
    49                 dfs2(p.right,2);
    50         }
    51     }
    52 
    53     void Mirror(TreeNode root) {
    54         if(root==null)
    55             return ;
    56         TreeNode t=root.left;
    57         root.left=root.right;
    58         root.right=t;
    59         Mirror(root.left);
    60         Mirror(root.right);
    61     }
    62     
    63     
    64 }
  • 相关阅读:
    第九周作业
    第八周作业
    第七周作业
    作业2
    作业1
    2019春总结作业
    第十四周总结
    十二周编程总结
    十一周编程总结
    第十周作业
  • 原文地址:https://www.cnblogs.com/llsq/p/8809890.html
Copyright © 2011-2022 走看看