美文网首页
[LeetCode]No.101 Symmetric Tree

[LeetCode]No.101 Symmetric Tree

作者: yuansc | 来源:发表于2016-10-09 18:58 被阅读20次

    链接: 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节点进行比较。

    相关文章

      网友评论

          本文标题:[LeetCode]No.101 Symmetric Tree

          本文链接:https://www.haomeiwen.com/subject/fnqmyttx.html