[Leetcode 题解 / 226] Invert Binar

作者: 卡巴拉的树 | 来源:发表于2016-08-05 10:23 被阅读420次

    Homebrew是OS X平台上的包管理工具,在用Mac的程序员基本都知道这个工具。
    HomeBrew的开发者是Max Howell。然而面试谷歌时却蛋疼了。Max Howell在Twitter发帖:


    twitter

    可见,会手写反转二叉树多么重要。正好Leetcode上有这个题目,下面进入正题。

    二叉树是数据结构里一个重要的概念。
    而反转二叉树的基本意思就是下图这样。
    Invert a binary tree.

         4
       /   \
      2     7
     / \   / \
    1   3 6   9
    
    

    to:

         4
       /   \
      7     2
     / \   / \
    9   6 3   1
    
    

    每一个节点的左右子树对换,左右子树的左右节点也需要交换,这种时候很容易想到的就是递归的方法。
    下面是在Leetcode 通过的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) {
            TreeNode* tmp;
            if(!root)
                return NULL;
            if(root->left)
                root->left=invertTree(root->left);
            if(root->right)
                root->right=invertTree(root->right);
            tmp=root->left;
            root->left=root->right;
            root->right=tmp;
            return root;     
        }
    };
    

    至于非递归的做法也很简单,借助一个队列就可以实现,在C++里,直接使用标准库的queue就可以。
    首先取根节点入队,再出队,交换它的左右节点,再将左右节点入队,这样就可以以层次遍历的方法,处理每一层的节点。

    /**
     * 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) {
            queue<TreeNode *> node_queue;
            
            if(root == NULL)
                return root;
            node_queue.push(root);
            while(node_queue.size()>0) 
            {
                TreeNode* pFrontNode = node_queue.front();
                node_queue.pop();
                TreeNode *tmp = pFrontNode->left;
                pFrontNode->left = pFrontNode->right;
                pFrontNode->right = tmp;
                if(pFrontNode->left)
                    node_queue.push(pFrontNode->left);
                if(pFrontNode->right)
                    node_queue.push(pFrontNode->right);
            }
            return root;
            
        }
    };
    

    最近在看Python,用Python实现也一样,递归解法:

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def invertTree(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            if root is None:
                return None
            root.left,root.right = self.invertTree(root.right),self.invertTree(root.left)
            return root
            
    

    非递归

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def invertTree(self, root):
            """
            :type root: TreeNode
            :rtype: TreeNode
            """
            queue = collections.deque()
            if root:
                queue.append(root)
            while queue:
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                node.left,node.right = node.right,node.left
            return root
    

    相关文章

      网友评论

        本文标题:[Leetcode 题解 / 226] Invert Binar

        本文链接:https://www.haomeiwen.com/subject/qsyhsttx.html