【LEETCODE】模拟面试-101-Symmetric Tree

图源:新生大学

题目:

https://leetcode.com/problems/symmetric-tree/


分析:

Input: So, we're given a binary tree.

**Output: ** If it's symmetric, we will return True, otherwise False.

**Corner case: ** If the tree is null, the output is True.

**Core case: **

The primitive idea is that, we may use two Deque on each level.

  • 1st one is for left part, 2nd one is for right part.
  • In 1st one, we add from first left child, at the same time, in 2nd one, we add from first right child.
  • Then compare the two nodes, if their values are same, then pop them together.
  • And continue to next child on this level.

Or, we can apply a helper function to optimize this process.

  • Every time we feed two parameters, 1st one is the most left child node, 2nd one is the most right child node.
  • If they are both null, they fit the condition.
  • If they are different, including the case that one is null, another has value, of course it's not symmetric.
  • If they have same values, then move to next level, where we should compare one.left with two.right, as well as, one.right with two.left. And make sure they are both True, the result can be True.

Java

/**
 * 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){
        //corner case
        if ( root == null )
            return true;
        
        //core logic
        return isSymmetric(root.left, root.right);
    }
    
    
    //helper function
    public boolean isSymmetric(TreeNode one, TreeNode two){
        //base case
        if( one == null || two == null ){
            if ( one == two )
                return true;
            else
                return false;
        }
        
        //current layer
        if ( one.val != two.val )
            return false;
        //next layer
        else
            return isSymmetric( one.left, two.right ) && isSymmetric( one.right, two.left );
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,151评论 0 10
  • 紧张与压力渐渐消去,一波平而一波起,十天的感冒咳嗽让我又一次体会到了健康的重要性,还有复杂的情绪让我有些焦虑,慢慢...
    Tiamo_7ef0阅读 767评论 0 0
  • ——【纪念】2017年的最后一次大师级教练课堂 昨儿个在大师班的复训课上做练习,一位美人脑洞大开,设计了个听音乐的...
    大喵教练百问阅读 3,047评论 3 2
  • 前几天邻家J姐姐回来了,我俩半年多没见面,刚在一起聚了聚。 J姐刚毕业一年,考研失败了(其实她本可以成功),教师资...
    字清沐阅读 3,860评论 3 2
  • 用心生活,用爱包容。 来自全国各地的黑马精英,大家晚上好, 我是本次的黑马营分享导师丹妮。 那么非常的高兴,受到商...
    A大凡子阅读 3,269评论 0 0