第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

二叉樹(shù)的遍歷問(wèn)題

二叉樹(shù)的遍歷問(wèn)題

開(kāi)心每一天1111 2019-02-20 09:20:10
最近在做leetcode上的題目,有一道題是要求交換二叉樹(shù)左右子樹(shù)。我一開(kāi)始沒(méi)有在函數(shù)體中加入如下代碼: if(root == null) return null; 結(jié)果發(fā)現(xiàn)出現(xiàn)空指針異常。我覺(jué)得上面這段代碼有點(diǎn)多余,但是OJ缺了它通過(guò)不了。麻煩各位大神幫忙解決一下小弟的困惑。下面貼上整個(gè)程序的代碼: public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } public TreeNode invertTree(TreeNode root){ if(root == null) return null; if(root.left == null && root.right == null) return root; TreeNode temp = root.left; root.left = root.right; root.right = temp; if(root.left != null) invertTree(root.left); if(root.right != null) invertTree(root.right); return root; } }
查看完整描述

3 回答

?
回首憶惘然

TA貢獻(xiàn)1847條經(jīng)驗(yàn) 獲得超11個(gè)贊

他的用例會(huì)不會(huì)有直接傳入null的? invertTree(null);

查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
LEATH

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊

你添加代碼,第一句代碼是
if(root.left == null && root.right == null)

         return root;

如果傳遞參數(shù)是null.那么root.left. 因?yàn)閞oot是null ,調(diào)用left屬性是報(bào)了異常
如果你屏蔽了異常那么.root.left==null 是true.
我并沒(méi)有了解過(guò)他的代碼,但是我猜代碼應(yīng)該是這樣的.

try{
invertTree(null);  //調(diào)用,
}catch{
create();  //創(chuàng)建樹(shù)的根節(jié)點(diǎn)方法
}
查看完整回答
反對(duì) 回復(fù) 2019-03-01
?
慕無(wú)忌1623718

TA貢獻(xiàn)1744條經(jīng)驗(yàn) 獲得超4個(gè)贊

不用這么麻煩。

void InvertTree(TreeNode* root)
{
        if(root)
        {
                TreeNode* tmp = root->left;
                root->left = root->right;
                root->right = tmp;
                InvertTree(root->left);
                InvertTree(root->right);
        }
}

這樣思路會(huì)不會(huì)簡(jiǎn)潔清晰一點(diǎn)?

查看完整回答
反對(duì) 回復(fù) 2019-03-01
  • 3 回答
  • 0 關(guān)注
  • 543 瀏覽
慕課專(zhuān)欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢(xún)優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)