翻转二叉树

来源:互联网 发布:智能语音助手软件 编辑:程序博客网 时间:2024/05/16 10:15

问题描述:翻转一棵二叉树

样例:

  1         1 / \       / \2   3  => 3   2   /       \  4         4
实现思路:从根出发开始操作,如果要操作的节点是空值,则不进行任何操作;否则,交换左右儿子,这里新建一个temp变量作为过渡。然后利用递归算法,分别对左右子树进行处理。

实现代码:

/**
 * 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
        TreeNode *temp;
        if(root==NULL)  
        return;
        else
        {
            temp=root->right;
            root->right=root->left;
            root->left=temp;
            invertBinaryTree(root->left);
            invertBinaryTree(root->right);
        }
        //swap(root->left,root->right);    
 

        //invertBinaryTree(root->left);  

        //invertBinaryTree(root->right);  大神给讲的swap()函数
    }
};

做题感想:此题要注意定义的temp变量是局部变量。做完后看别的同学做的更简单,是什么swap()函数,好吧以前没好好学,不知道是啥。

1 0
原创粉丝点击