IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    Invert binary tree

    Lawrence发表于 2017-12-22 00:00:00
    love 0

    A problem that Homebrew's author complained.


    Invert a binary tree. Problem from leetcode.

    Here's the input:

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

    and the out put looks like:

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

    This problem was inspired by this tweet.

    Here's the solution implemented in 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(null != root){
                TreeNode leftChild = root.left;
                root.left = root.right;
                root.right = leftChild;
                root.left = invertTree(root.left);
                root.right = invertTree(root.right);
            }
            return root;
        }
    }
    

    There's much different logic behind software engineering with computer science. Max replied this question about it on quora.com after 2 years.



沪ICP备19023445号-2号
友情链接