https://leetcode.com/problems/symmetric-tree/
判斷一個二元樹是否鏡像,是的話回傳TRUE不是的話回傳FALSE。
利用遞迴尋訪特性,將左節點和右節點相互比較,當條件不符合時直接跳出。
也可以用非遞迴的方式去解,利用堆疊先進後出的觀念去做處理。
bool isSymmetric(struct TreeNode* root) {
return isMirror(root, root);
}
bool isMirror(struct TreeNode *root1, struct TreeNode *root2)
{
if (root1 == NULL && root2 == NULL)
return true;
if (root1 && root2 && root1->val == root2->val)
return isMirror(root1->left, root2->right) &&
isMirror(root1->right, root2->left);
return false;
}
var isSymmetric = function(root) {
if (!root) return true
const stack = []
stack.push(root.left, root.right)
while (stack.length) {
const left = stack.pop()
const right = stack.pop()
if (left === right) continue
if (!left || !right || left.val !== right.val) return false
stack.push(left.left, right.right)
stack.push(left.right, right.left)
}
return true
};
https://github.com/SIAOYUCHEN/leetcode
https://ithelp.ithome.com.tw/users/20100009/ironman/2500
https://ithelp.ithome.com.tw/users/20113393/ironman/2169
https://ithelp.ithome.com.tw/users/20107480/ironman/2435
https://ithelp.ithome.com.tw/users/20107195/ironman/2382
https://ithelp.ithome.com.tw/users/20119871/ironman/2210
https://ithelp.ithome.com.tw/users/20106426/ironman/2136
Remember what to remember, forget what to forget. Change what can be changed, accept what can not be changed
記住該記住的,忘記該忘記的。改變能改變的,接受不能改變的