Leetcode模拟面试

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

2017-01-03  本文已影响86人  不会停的蜗牛
图源:新生大学

题目:

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.

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


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 );
    }
    
}
上一篇 下一篇

猜你喜欢

热点阅读