java - 二叉树的遍历问题
天蓬老师
天蓬老师 2017-04-17 15:29:01
0
3
672

最近在做leetcode上的题目,有一道题是要求交换二叉树左右子树。我一开始没有在函数体中加入如下代码:

if(root == null) return null;

结果发现出现空指针异常。我觉得上面这段代码有点多余,但是OJ缺了它通过不了。麻烦各位大神帮忙解决一下小弟的困惑。下面贴上整个程序的代码:

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; } }
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all (3)
大家讲道理

Will his use case directly pass in null?invertTree(null);

    洪涛

    You add code, the first code is
    if(root.left == null && root.right == null)

    return root;

    If the passed parameter is null, then root.left. Because root is null, calling the left attribute will report an exception
    If you block the exception, then .root.left==null is true.
    I don’t I haven’t understood his code, but I guess the code should be like this.

    try{ invertTree(null); //调用, }catch{ create(); //创建树的根节点方法 }
      Peter_Zhu

      No need to go to such trouble.

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

      Would this idea be more concise and clear?

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!