翻转二叉树

来源:互联网 发布:js改变display属性 编辑:程序博客网 时间:2024/06/07 21:33

题目:

翻转一棵二叉树

样例
  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 ;
        TreeNode *T=root->left;
        //int t=root->left->val;
        root->left=root->right;
        root->right=T;
        if(root->left!=NULL) {invertBinaryTree(root->left);}
        if(root->right!=NULL) {invertBinaryTree(root->right);}
    }
};

感想:

这道题挺简单,不过当时上课我没听,没看课件自己写出来了,也是挺高兴的。

0 0