LeetCode題庫解答與分析——#101. 對稱二叉樹SymmetricTree
阿新 • • 發佈:2019-02-07
給定一個二叉樹,檢查它是否是它自己的映象(即,圍繞它的中心對稱)。
例如,這個二叉樹 [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
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]
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
個人思路:
把根節點的左右節點看做兩棵樹的根節點,與相同的樹思路類似,利用深度優先搜尋同時遍歷兩棵樹的所有節點,不同的是,要以對稱的方向將兩棵樹的節點進棧、出棧,如左樹的左子節點和右樹的右子節點同時進棧,同樣在每次出棧時比較兩數值是否相等,進棧後比較棧長度是否一致,如有不同則立刻返回false,堅持到最後則返回true。
程式碼(Java):
/** * 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=null,q=null; if(root.left!=null){p=root.left;} if(root.right!=null){q=root.right;} if(p!=null) pstack.push(p); if(q!=null) qstack.push(q); if(pstack.size()!=qstack.size()){return false;} while (!pstack.isEmpty()&&!qstack.isEmpty()) { p=pstack.pop(); q=qstack.pop(); if(p.val!=q.val){return false;} if(p.right!=null){pstack.push(p.right);} if(q.left!=null){qstack.push(q.left);} if(pstack.size()!=qstack.size()){return false;} if(p.left!=null){pstack.push(p.left);} if(q.right!=null){qstack.push(q.right);} if(pstack.size()!=qstack.size()){return false;} } return pstack.size()==qstack.size(); } }