交換左右孩子-leetcode-226. 翻轉二叉樹

xiaomingds發表於2020-10-16

226. 翻轉二叉樹

翻轉一棵二叉樹。

示例:

  輸入: 

     4
   /   \
  2     7
 / \   / \
1   3 6   9
輸出:    
     4
   /   \
  7     2
 / \   / \
9   6 3   1

 利用層次遍歷交換左右結點

  public TreeNode invertTree(TreeNode root) {
           if(root == null)
                return root;
           Queue<TreeNode>queue = new LinkedList<TreeNode>();
           queue.offer(root);
           while(!queue.isEmpty()){
                    TreeNode node = queue.poll();
                    TreeNode rnode = node.right;
                    node.right = node.left;
                    node.left = rnode;
                    if(node.left != null)
                        queue.offer(node.left);
                    if(node.right !=null)
                        queue.offer(node.right);
        
           }
           return root;
    }

遞迴

   public TreeNode invertTree(TreeNode root) {
           if(root == null)
                return root;
            TreeNode lroot = invertTree(root.left);
            TreeNode rroot = invertTree(root.right);
            root.left = rroot;
            root.right = lroot;  
           return root;
    }

 

 

相關文章