您的位置:首页 > 其它

翻转二叉树

2017-04-19 10:56 148 查看
题目:

翻转一棵二叉树

样例

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

        TreeNode *node;

        if(root==NULL) return;

        else{

            node=root->right;

            root->right=root->left;

            root->left=node;

            invertBinaryTree(root->left);

            invertBinaryTree(root->right);

            }

    }

};

感悟:

注意要增加一个过渡节点,从而实现节点的交换。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: