• [Leetcode]101. Symmetric Tree


    Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

    For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    But the following [1,2,2,null,3,null,3] is not:

        1
       / 
      2   2
          
       3    3

    思路:设两个游标p,q同时递归,递归的方向相反。即当p往左走时,q往右走。p往右走时,q往左走。
    如果这棵树是镜像的,那么最后 p 和 q一定是同时到达null位置,并且在这个过程中,p,q节点的
    值是相同的。


    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isSymmetric(TreeNode root) {
            if (root==null)
                return true;
            return judge(root.left,root.right);
        }
    
        private  boolean judge(TreeNode p,TreeNode q){
            if (p==null&&q==null)               //同时到达null位置,说明树是镜像的
                return true;
            if (p==null&&q!=null)
                return false;
            if (p!=null&&q==null)
                return false;
            if (p.val!=q.val)
                return false;
            return judge(p.left,q.right)&&judge(p.right,q.left);
        }
    }
  • 相关阅读:
    GUI编程
    Markdown学习
    [python3]正则表达式
    python3_json&pickle
    python3_module_sys
    python3_module_os
    Python3_module_random
    Pyhton3_module_time()
    Python3 正则表达式 Regular Expression
    Python循环对象
  • 原文地址:https://www.cnblogs.com/David-Lin/p/7783470.html
Copyright © 2020-2023  润新知