劍指offer---二叉樹的鏡像---java實現

來源:互聯網
上載者:User
題目描述

操作給定的二叉樹,將其變換為源二叉樹的鏡像。  輸入描述:

二叉樹的鏡像定義:源二叉樹

        8

       /  \

      6   10

     / \  / \

     5  7 9 11

     鏡像二叉樹

        8

       /  \

      10   6

     / \  / \

     11 9 7  5

其實就是交換二叉樹的左右子樹,可用遞迴實現:

交換根節點的左右孩子,再分別對左孩子進行鏡像和右孩子進行鏡像

代碼:

import java.util.LinkedList;public class MirrorTest{//遞迴   public void Mirror(TreeNode root)   {   if(root == null)return;   else    {             TreeNode temp = root.left;//交換根節點的左右孩子       root.left = root.right;       root.right = temp;       Mirror(root.left);//鏡像根節點的左孩子的左右子樹       Mirror(root.right);//鏡像根節點的右孩子的左右子樹        }   }      //非遞迴實現   public void Mirror1(TreeNode root)   {   if(root == null)   {   return;   } LinkedList<TreeNode> stack = new LinkedList<TreeNode>();//藉助於輔助棧 TreeNode current = null;//存放出棧的棧頂元素 TreeNode temp = null; stack.push(root);//將根項目入棧 while(!stack.isEmpty()) {current = stack.pop();//將根項目出棧 交換根項目的左右子樹if(current.left != null || current.right != null)//若左右孩子不為空白則交換左右孩子{temp = current.left;current.left = current.right;current.right = temp;}//將根項目的左右孩子壓入棧中  if(current.left != null)stack.push(current.left);if(current.right != null)stack.push(current.right); }      }}



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.