226. 翻轉(zhuǎn)二叉樹(shù)
問(wèn)題描述
翻轉(zhuǎn)一棵二叉樹(shù)。
解題思路
遞歸。
代碼實(shí)現(xiàn)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
TreeNode temp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(temp);
return root;
}
}
101. 對(duì)稱二叉樹(shù)
問(wèn)題描述
給定一個(gè)二叉樹(shù)渐逃,檢查它是否是鏡像對(duì)稱的
解題思路
通過(guò)遞歸判斷左右子樹(shù)樹(shù)是否鏡像對(duì)稱
代碼實(shí)現(xiàn)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode p, TreeNode q) {
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
return p.val == q.val && check(p.left, q.right) && check(p.right, q.left);
}
}