【LeetCode】Invert Binary Tree 翻转二叉树

来源:互联网 发布:开淘宝店空挂商品 编辑:程序博客网 时间:2024/05/03 08:25

翻转一棵二叉树

样例  1         1 / \       / \2   3  => 3   2   /       \  4         4

挑战
递归固然可行,能否写个非递归的?

(1)Java

//Version 1 : Recursionpublic class InvertBinaryTree {    /*    * @param root: a TreeNode, the root of the binary tree    * @return: nothing    */    public void invertBinaryTree(TreeNode root) {        if(root == null){            return ;        }        TreeNode temp = root.left;        root.left = root.right;        root.right = temp;        invertBinaryTree(root.left);        invertBinaryTree(root.right);    }}

(2)C++

class Solution {    public:    /**     * @param root: a TreeNode, the root of the binary tree     * @return: nothing     */    void invertBinaryTree(TreeNode *root) {        // write your code here        dfs(root);    }    private:    void dfs(TreeNode *node) {        TreeNode *left = node->left, *right = node->right;        node->left = right; node->right = left;        if (left!=NULL) dfs(left);        if (right!=NULL) dfs(right);    }};//Version 2: class Solution {private:    void dfs(TreeNode* root){        if(!root){            return;        }        TreeNode* temp = root->left;        root->left = root->right;        root->right = temp;        dfs(root->left);        dfs(root->right);    }public:    /*     * @param root: a TreeNode, the root of the binary tree     * @return: nothing     */    void invertBinaryTree(TreeNode * root) {        if(!root){            return;        }        dfs(root);    }};
原创粉丝点击