天天看點

226 Invert Binary Tree 翻轉二叉樹

翻轉一棵二叉樹。

     4

    / \

   2   7

 / \  / \

1  3 6  9

轉換為:

   7    2

 / \    / \

9  6  3   1

詳見:https://leetcode.com/problems/invert-binary-tree/

Java實作:

遞歸實作:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        TreeNode node=root.left;
        root.left=invertTree(root.right);
        root.right=invertTree(node);
        return root;
    }
}      

疊代實作:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null){
            return null;
        }
        LinkedList<TreeNode> que=new LinkedList<TreeNode>();
        que.offer(root);
        while(!que.isEmpty()){
            TreeNode node=que.poll();
            TreeNode tmp=node.left;
            node.left=node.right;
            node.right=tmp;
            if(node.left!=null){
                que.offer(node.left);
            }
            if(node.right!=null){
                que.offer(node.right);
            }
        }
        return root;
    }
}      

C++實作:

方法一:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==nullptr)
        {
            return nullptr;
        }
        TreeNode *node=root->left;
        root->left=invertTree(root->right);
        root->right=invertTree(node);
        return root;
    }
};      

方法二:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* invertTree(TreeNode* root) {
        if(root==nullptr)
        {
            return nullptr;
        }
        queue<TreeNode*> que;
        que.push(root);
        while(!que.empty())
        {
            TreeNode *node=que.front();
            que.pop();
            TreeNode *tmp=node->left;
            node->left=node->right;
            node->right=tmp;
            if(node->left)
            {
                que.push(node->left);
            }
            if(node->right)
            {
                que.push(node->right);
            }
        }
        return root;
    }
};