判斷對稱二叉樹
阿新 • • 發佈:2020-06-29
題目描述
請實現一個函式,用來判斷一棵二叉樹是不是對稱的。注意,如果一個二叉樹同此二叉樹的映象是同樣的,定義其為對稱的。給定一個二叉樹,檢查它是否是映象對稱的。
例如,二叉樹[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
題目分析
如果對第二種情況遍歷得到的輸出結果與對它的映象二叉樹遍歷得到的輸出結果相同。
但是第二種情況不是對稱二叉樹。
考慮在null位置補加“#”。
採用層序遍歷。左:1,2,2,#,3,#,3;右:1,2,2,3,#,3,#。這樣通過比較兩個字串就可以判斷一個二叉樹與其映象二叉樹
是否相等。
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { String str = new String("");void tran1(TreeNode root) { if (root != null) { str=str.concat(String.valueOf(root.val)); tran1(root.left); tran1(root.right); }else{ str=str.concat("#"); } } void tran2(TreeNode root) { if (root != null) { TreeNode temp= root.left; root.left = root.right; root.right = temp; tran2(root.left); tran2(root.right); } } boolean isSymmetrical(TreeNode pRoot) { tran1(pRoot); String str1 = new String(""); str1 = str; str = ""; tran2(pRoot); tran1(pRoot); String str2 = new String(""); str2 = str; return str1.equals(str); } }