[LeetCode 226] Invert Binary Tree

Invert a binary tree.

     4
   /   \
  2     7
 / \   / \
1   3 6   9
to
     4
   /   \
  7     2
 / \   / \
9   6 3   1

递归的方法:

/**
 * 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* invertTree(TreeNode* root) {

		if (root == NULL)
			return root;
		
		TreeNode *tmp = root->left;
		root->left = invertTree(root->right);
		root->right = invertTree(root->left);
		return root;
	}
};



非递归的方法:

lass Solution {
public:
	TreeNode* invertTree(TreeNode* root) {
		queue tree_ueue;
		if(root == NULL)
			return root;
		tree_queue.push(root);
		while(!ree_queue.empty())
		{
			TreeNode* pNode = tree_queue.front();
			tree_queue.pop();
			TreeNode* pTmp = pNode->left;
			pNode->left = pNode->right;
			pNode->right = pTmp;
			if(pNode->left)
				tree_queue.push(pNode->left);
			if(pNode ->right)
				tree_queue.push(pNode->right);
		}
		return root;
	}
};




你可能感兴趣的:(LeetCode)