LeetCode 226. 翻转二叉树(DFS BFS)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 226. 翻转二叉树(DFS BFS)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目信息
- 2. 解題
- 2.1 DFS
- 2.2 BFS
1. 題目信息
翻轉(zhuǎn)一棵二叉樹。
示例:輸入:4/ \2 7/ \ / \ 1 3 6 9輸出:4/ \7 2/ \ / \ 9 6 3 1來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/invert-binary-tree
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請注明出處。
《劍指Offer》同題:面試題27. 二叉樹的鏡像
2. 解題
2.1 DFS
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class Solution { public:TreeNode* invertTree(TreeNode* root) { if(root){swap(root->left,root->right);invertTree(root->left);invertTree(root->right);}return root;} }; class Solution { public:TreeNode* mirrorTree(TreeNode* root) {if(!root)return root;mirrorTree(root->left);mirrorTree(root->right);swap(root->left,root->right);return root;} };2.2 BFS
利用隊列,按層遍歷
總結(jié)
以上是生活随笔為你收集整理的LeetCode 226. 翻转二叉树(DFS BFS)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 47. 全排列 II(
- 下一篇: LeetCode 1137. 第 N 个