美文网首页
LeetCode 226 (Invert Binary Tree

LeetCode 226 (Invert Binary Tree

作者: Lcap | 来源:发表于2019-05-25 11:13 被阅读0次

    LeetCode:226 invert-binary-tree
    先序遍历:

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null)
                return null;
            
            if(root.left != null)
                invertTree(root.left);
            if(root.right != null) 
                invertTree(root.right);
            
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            
            return root;
        }
    }
    

    中序遍历:

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null)
                return null;
            if(root.left != null)
                invertTree(root.left);
           
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
            
            0if(root.right != null) 
                invertTree(root.right);
            
            return root;
        }
    }
    

    后序遍历:

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null)
                return null;
            if(root.left != null)
                invertTree(root.left);
                if(root.right != null) 
                invertTree(root.right);
            TreeNode temp = root.left;
            root.left = root.right;
            root.right = temp;
    
            return root;
        }
    }
    

    层序遍历:

    class Solution {
       public TreeNode invertTree(TreeNode root) {
            Queue<TreeNode> list = new LinkedList<>();
            
            if(root == null)
                return null;
            
            list.add(root);
            
            while(!list.isEmpty()) {
                TreeNode node = list.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if(node.left != null)
                    list.add(node.left);
                if(node.right != null)
                    list.add(node.right);
            }
            
            return root;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode 226 (Invert Binary Tree

          本文链接:https://www.haomeiwen.com/subject/wodazqtx.html