当前位置:网站首页>Leetcode-101-symmetric binary tree

Leetcode-101-symmetric binary tree

2022-06-25 18:42:00 z754916067

subject

 Insert picture description here

Ideas

  1. It's a binary tree anyway , Think about recursion first , See if you can do it recursively .
  2. I don't think I can do it , And I thought about whether I could do it with traversal , Go through the array first , If it is symmetrical, it should conform to certain rules ?
  3. Middle order traversal is very suitable for , See whether the array is symmetrical to the root node .
  4. Because the root node is the same as the left and right subtrees , So for null, Special treatment is also required , The scope is [-100,100], Treat it as 101 that will do .

Code

    ArrayList<Integer> ll = new ArrayList<>();
    public boolean isSymmetric(TreeNode root) {
    
        // First, the binary tree is traversed in middle order   Add numbers to ll in 
        InOrder(root);
        // Find the location of the root node   Find out whether it is axisymmetric according to this position   If not, returns false
        // Location 
        int local = ll.indexOf(root.val);
        // about 
        int left=0,right = ll.size()-1;
        while(left<=local || right>=local){
    
            if(ll.get(left++)!=ll.get(right--)) return false;
        }
        return true;
    }
    public void InOrder(TreeNode root){
    
        if(root.left!=null) InOrder(root.left);
        if(root.left==null&&root.right!=null) ll.add(101);

        ll.add(root.val);
        if(root.right!=null) InOrder(root.right);
        if(root.right==null&&root.left!=null) ll.add(101);

        return;
    }
原网站

版权声明
本文为[z754916067]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251828294179.html