力扣0101——对称二叉树

对称二叉树

难度:简单

题目描述

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例1

输入: root = [1,2,2,3,4,4,3]
输出: true

示例2

输入: root = [1,2,2,null,3,null,3]
输出: false

题解

和第 0100 题相同的解法,利用回溯法求解,不同的是比较左右两个子树

想法代码

public class TreeNode
{
    public int val;
    public TreeNode left;
    public TreeNode right;
    public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null)
    {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution
{
    public static void Main(string[] args)
    {
        TreeNode root = new TreeNode(1)
        {
            left = new TreeNode(2)
            {
                left = new TreeNode(3),
                right = new TreeNode(4)
            },
            right = new TreeNode(2)
            {
                left = new TreeNode(3),
                right = new TreeNode(4)
            }
        };
        Solution solution = new Solution();
        Console.WriteLine(solution.IsSymmetric(root));
    }

    public bool IsSymmetric(TreeNode root)
    {
        return BackTrack(root.left,root.right);
    }

    public bool BackTrack(TreeNode p, TreeNode q)
    {
        if (p == null && q == null)
        {
            return true;
        }

        if (p == null || q == null)
        {
            return false;
        }
        return p.val == q.val && BackTrack(p.left, q.right) && BackTrack(p.right,q.left);
    }
}

你可能感兴趣的:(算法进修,leetcode,算法,职场和发展)