[LeetCode]No.101 Symmetric Tree

链接: https://leetcode.com/problems/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

Note:Bonus points if you could solve it both recursively and iteratively.

分析:
这道题要求的是判断一颗二叉树是不是对称二叉树, 可以白话一点说 就是从顶点竖直线进行折叠,树的两边是否能完美对称。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null){
            return true;
        }
        return isMirror(root.left, root.right);
    }
    public boolean isMirror(TreeNode left, TreeNode right) {
        if(left == null && right == null) {
            return true;
        }
        if(left == null && right!=null) {
            return false;
        }
        if(left!=null && right == null) {
            return false;
        }
        if(left.val != right.val) {
            return false;
        }
        return isMirror(left.left, right.right) && isMirror(left.right, right.left);
    }
}

比较笨的方法递归,递归的去比较节点的val,val相同则继续比较子节点,left节点的right节点与right节点的left节点进行比较。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容