LeetCode(算法)- 101. 对称二叉树

Posted 放羊的牧码

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode(算法)- 101. 对称二叉树相关的知识,希望对你有一定的参考价值。

题目链接:点击打开链接

题目大意:

解题思路:

相关企业

  • 字节跳动
  • 谷歌(Google)
  • 微软(Microsoft)
  • Facebook
  • 亚马逊(Amazon)
  • 优步(Uber)
  • Paypal
  • 彭博(Bloomberg)

AC 代码

  • Java
/**
 * Definition for a binary tree node.
 * public class TreeNode 
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() 
 *     TreeNode(int val)  this.val = val; 
 *     TreeNode(int val, TreeNode left, TreeNode right) 
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     
 * 
 */

// 解决方案(1)
class Solution 

    private boolean ok = true;

    public boolean isSymmetric(TreeNode root) 
        if (null == root || root.left == null && root.right == null) 
            return true;
        
        if (root.left == null || root.right == null) 
            return false;
        
        dfs(root.left, root.right);
        return ok;
    

    private void dfs(TreeNode l, TreeNode r) 
        if (!ok) 
            return;
        
        if (null == l && null == r) return;
        if (null == l || null == r) 
            ok = false;
            return;
        
        if (l.val != r.val) 
            ok = false;
            return;
        

        dfs(l.left, r.right);
        dfs(l.right, r.left);
    


// 解决方案(2)
class Solution 
    public boolean isSymmetric(TreeNode root) 
        return root == null || recur(root.left, root.right);
    
    boolean recur(TreeNode L, TreeNode R) 
        if(L == null && R == null) return true;
        if(L == null || R == null || L.val != R.val) return false;
        return recur(L.left, R.right) && recur(L.right, R.left);
    
  • C++
/**
 * Definition for a binary tree node.
 * struct TreeNode 
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) 
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) 
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) 
 * ;
 */
class Solution 
public:
    bool isSymmetric(TreeNode* root) 
        return root == nullptr || recur(root->left, root->right);
    
private:
    bool recur(TreeNode* L, TreeNode* R) 
        if(L == nullptr && R == nullptr) return true;
        if(L == nullptr || R == nullptr || L->val != R->val) return false;
        return recur(L->left, R->right) && recur(L->right, R->left);
    
;

以上是关于LeetCode(算法)- 101. 对称二叉树的主要内容,如果未能解决你的问题,请参考以下文章

leetcode算法101.对称二叉树

101. 对称二叉树

101. 对称二叉树

LeetCode-101-对称二叉树

LeetCode101----对称二叉树

LeetCode刷题101-简单-对称二叉树