【劍指offer】面試題27. 二叉樹的鏡像

解題思路

先序遍歷
首先判斷左右節點是否都不爲null,如果不爲,則進行交換;
然後對其左子樹鏡像,再對其右子樹鏡像

代碼

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    	TreeNode* mirrorTree(TreeNode* root) {
		if (root == NULL) return NULL;//爲空不進行交換
		else if(root->left!=NULL||root->right!=NULL)//左節點和右節點都不爲null時就進行交換
		{
			TreeNode* temp = root->left;
			root->left = root->right;
			root->right = temp;
            if(root->left!=NULL) mirrorTree(root->left);//左子樹存在則進行鏡像
			if(root->right!=NULL) mirrorTree(root->right);//右子樹存在則進行鏡像
		}
		return root;
	}
};
發佈了99 篇原創文章 · 獲贊 19 · 訪問量 8174
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章