開(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 回答

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)方法
}

慕無(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)?
添加回答
舉報(bào)
0/150
提交
取消