LeetCode 101. Symmetric Tree 對稱二叉樹
阿新 • • 發佈:2019-01-24
題目:
給定一個二叉樹,檢查它是否是映象對稱的。
例如,二叉樹 [1,2,2,3,4,4,3]
是對稱的。
1 / \ 2 2 / \ / \ 3 4 4 3
但是下面這個 [1,2,2,null,3,null,3]
則不是映象對稱的:
1 / \ 2 2 \ \ 3 3
說明:
如果你可以運用遞迴和迭代兩種方法解決這個問題,會很加分。
解題思路:
對這棵樹同時進行優先訪問左子樹的前序遍歷和優先訪問右子樹的前序遍歷,判斷當前訪問到的兩個節點是不是相等。
程式碼實現:
遞迴:
/** * Definition for a binary tree node.* public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { TreeNode p = root; TreeNode q = root; return helper(p, q); } private boolean helper(TreeNode p, TreeNode q) {// 判斷有沒有節點為null的情況,一句話搞定 if (p == null || q == null) return p == q; return (p.val == q.val) && helper(p.left, q.right) && helper(p.right, q.left); } }
迭代:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; }* } */ class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) return true; Stack<TreeNode> pStack = new Stack<TreeNode>(); Stack<TreeNode> qStack = new Stack<TreeNode>(); TreeNode p = root; TreeNode q = root; while (p != null && q != null) { // 當前節點不相等,返回false if (!isEqual(p, q)) return false; if (p.right != null) pStack.push(p.right); if (q.left != null) qStack.push(q.left); p = p.left; q = q.right; if (p == null && q == null && !pStack.isEmpty() && !qStack.isEmpty()) { p = pStack.pop(); q = qStack.pop(); } } return p == q; } private boolean isEqual(TreeNode p, TreeNode q) { boolean children = true; if (p == null || q == null) return p == q; if (p.left == null || q.right == null) children = children && (p.left == q.right); if (p.right == null || q.left == null) children = children && (p.right == q.left); return (p.val == q.val) && children; } }