101. 对称二叉树

深度优先搜索
比较左右节点是否相同,然后比较左子树的左节点和右子树的右节点、左子树的右节点和右子树的左节点。

/**
 * 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;
 *     }
 * }
 */
class Solution {
    public boolean isSymmetric(TreeNode root) {
        if (root == null) return true;
        return dfs(root.left, root.right);
    }

    public boolean dfs (TreeNode left, TreeNode right) {
        if (left == null && right == null) return true;
        if (left == null || right == null) return false;
        if (left.val == right.val) return dfs(left.left, right.right) && dfs(left.right, right.left);
        else return false;
    }
}

你可能感兴趣的:(LeetCode,数据结构,算法,深度优先)