翻转二叉树

来源:互联网 发布:女朋友胸很大知乎 编辑:程序博客网 时间:2024/05/29 17:18

问题描述:

翻转一棵二叉树

样例

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

解题感想:

temp的使用,root==NULL时,直接返回。


0 0
原创粉丝点击