Leetcode 101: Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public bool IsSymmetric(TreeNode root) { 12 if (root == null) return true; 13 14 return DFS(root.left, root.right); 15 } 16 17 private bool DFS(TreeNode node1, TreeNode node2) 18 { 19 if (node1 == null || node2 == null) return node1 == null && node2 == null; 20 21 return node1.val == node2.val && DFS(node1.left, node2.right) && DFS(node1.right, node2.left); 22 } 23 }