问题描述:
翻转一棵二叉树
样例:
1 1
/ \ / \
2 3 => 3 2
/ \
4 4
解题思路:
前序遍历先找到叶子结点,从叶子节点开始往上回溯,每个结点的左子树和右子树交换。
代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
if (root== NULL) return;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
TreeNode *temp= root->left;
root->left= root->right;
root->right= temp;
}
};
感想:
先从根节点和先从叶子结点交换原理是一样的。