zoukankan      html  css  js  c++  java
  • LeetCode -- Invert Binary Tree

    Question:

    Invert a binary tree.

         4
       /   
      2     7
     /    / 
    1   3 6   9

    to

         4
       /   
      7     2
     /    / 
    9   6 3   1

    Trivia:
    This problem was inspired by this original tweet by Max Howell:

    Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

    Analysis:

    问题描述:给出一个二叉树,然后将它的左右子树置换。

    思路:这种题目首先应该反射到递归。用递归有两个条件:return 语句的书写和递归语句的书写。在这道题目中,只要一个节点有任何左节点或者右节点,则应该将他们置换。因此只要非空就置换

    Answer:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode invertTree(TreeNode root) {
          if(root == null)
                  return root;
          TreeNode t = root.left;
          root.left = root.right;
          root.right = t;
          invertTree(root.left);
          invertTree(root.right);
          return root;
        }
    }
  • 相关阅读:
    Docker contanier comunication with route
    Event Sourcing
    Event Sourcing
    Event Sourcing
    .Net async
    安装Docker
    【JQuery】数据
    【JQuery】遍历
    【JQuery】css操作
    【JQuery】文档操作
  • 原文地址:https://www.cnblogs.com/little-YTMM/p/4841554.html
Copyright © 2011-2022 走看看