【Leetcode 226】Invert Binary Tree (C++)

题目

Invert a binary tree.

Example:

Input:

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

Output:

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

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

分析

采用深度遍历。

需要注意的是,有可能根结点为NULL值。

源代码

TreeNode* invertTree(TreeNode* root) {
	if (root == NULL || (root->left == NULL && root->right == NULL))
		return root;
	else
	{
		TreeNode *temp;
		temp = root->left;
		root->left = root->right;
		root->right = temp;
	}
	if (root->left != NULL)
		invertTree(root->left);
	if (root->right != NULL)
		invertTree(root->right);
	return root;
}

 

你可能感兴趣的:(深度遍历)