LeeCode-226. 翻轉(zhuǎn)二叉樹(shù)
要求
給你一棵二叉樹(shù)的根節(jié)點(diǎn) root ,翻轉(zhuǎn)這棵二叉樹(shù),并返回其根節(jié)點(diǎn)。 如下圖所示反轉(zhuǎn)所有左右節(jié)點(diǎn).
解題思路
與94題類似,采用遞歸調(diào)用遍歷子節(jié)點(diǎn)。在基本結(jié)構(gòu)中,先調(diào)換左右節(jié)點(diǎn),再對(duì)左右節(jié)點(diǎn)內(nèi)部遞歸調(diào)用本身。
實(shí)現(xiàn)代碼
TreeNode* invertTree(TreeNode* root) {
if(root)
{
TreeNode* temp=root->left;
root->left=root->right;
root->right=temp;
if(root->left)
invertTree(root->left);
if(root->right)
invertTree(root->right);
}
return root;
}
作者:robot2017
出處:http://www.rzrgm.cn/stephen2023/p/18397456
版權(quán):本文版權(quán)歸作者和博客園共有
轉(zhuǎn)載:歡迎轉(zhuǎn)載,但未經(jīng)作者同意,必須保留此段聲明;必須在文章中給出原文連接;否則必究法律責(zé)任
出處:http://www.rzrgm.cn/stephen2023/p/18397456
版權(quán):本文版權(quán)歸作者和博客園共有
轉(zhuǎn)載:歡迎轉(zhuǎn)載,但未經(jīng)作者同意,必須保留此段聲明;必須在文章中給出原文連接;否則必究法律責(zé)任
浙公網(wǎng)安備 33010602011771號(hào)