search

Home  >  Q&A  >  body text

java - 二叉树的遍历问题

最近在做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;
     }
}
天蓬老师天蓬老师2822 days ago752

reply all(3)I'll reply

  • 大家讲道理

    大家讲道理2017-04-17 15:31:01

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

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 15:31:01

    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();  //创建树的根节点方法
    }

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 15:31:01

    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?

    reply
    0
  • Cancelreply