zoukankan      html  css  js  c++  java
  • 翻转二叉树(深搜-先序遍历-交换Node)

    题目:翻转二叉树,例如

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

    已知二叉树的节点定义如下:

    class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode(int x) { val = x; }
    }

    分析:该题有个小故事: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.

    该题可以使用深搜中的先序遍历的思路,依次交换左右TreeNode,注意是交换TreeNode,而不是交换TreeNode的值。下面是翻转的过程:

         4                           4                                   4                        4
       /                           /                                  /                       / 
      2     7         ->           7    2           ->                 7    2          ->       7   2              
     /    /                     /    /                            /   /                  /  / 
    1  3  6   9                  6   9 1   3                         9  6 1   3               9  6 3  1 

    AC代码如下:

        public TreeNode invertTree(TreeNode root) {
            if (root == null) {
                return null;
            }
            TreeNode tmp = root.left;
            root.left = root.right;
            root.right = tmp;
            
            invertTree(root.left);
            invertTree(root.right);
            return root;
        }
  • 相关阅读:
    【leetcode】反转字符串
    【leetcode】反转字符串 II
    053-669
    053-668
    053-667
    053-666
    053-665
    053-664
    053-663
    053-662
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4915006.html
Copyright © 2011-2022 走看看