[Leetcode]101. Symmetric Tree
阿新 • • 發佈:2017-11-04
blog enter following lean 位置 his class 兩個 oot
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
思路:設兩個遊標p,q同時遞歸,遞歸的方向相反。即當p往左走時,q往右走。p往右走時,q往左走。
如果這棵樹是鏡像的,那麽最後 p 和 q一定是同時到達null位置,並且在這個過程中,p,q節點的
值是相同的。
/** * 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; returnjudge(root.left,root.right); } private boolean judge(TreeNode p,TreeNode q){ if (p==null&&q==null) //同時到達null位置,說明樹是鏡像的 return true; if (p==null&&q!=null) return false; if (p!=null&&q==null) returnfalse; if (p.val!=q.val) return false; return judge(p.left,q.right)&&judge(p.right,q.left); } }
[Leetcode]101. Symmetric Tree