[LeetCode] Symmetric Tree 判斷對稱樹
阿新 • • 發佈:2018-11-27
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
判斷二叉樹是否是平衡樹,比如有兩個節點n1, n2,我們需要比較n1的左子節點的值和n2的右子節點的值是否相等,同時還要比較n1的右子節點的值和n2的左子結點的值是否相等,以此類推比較完所有的左右兩個節點。我們可以用遞迴和迭代兩種方法來實現,寫法不同,但是演算法核心都一樣。
public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } return isSameTree(root.left, root.right); } public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null || q == null) { return p == q; } boolean f = p.val == q.val; boolean f2 = isSameTree(p.left, q.right); boolean f3 = isSameTree(p.right, q.left); return f && f2 && f3; }
類似問題:
1. 222Count Complete Tree
2. 110Balanced Binary Tree