• 226. Invert Binary Tree


    Invert a binary tree.

    Example:

    Input:

         4
       /   
      2     7
     /    / 
    1   3 6   9

    Output:

         4
       /   
      7     2
     /    / 
    9   6 3   1
    /**
     * 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) {
            Queue<TreeNode> q = new LinkedList();
            if(root != null) q.offer(root);
            
            while(!q.isEmpty()){
                TreeNode p = q.poll();
                TreeNode tmp = p.left;
                p.left = p.right;
                p.right = tmp;
                
                if(p.left != null) q.offer(p.left);
                if(p.right != null) q.offer(p.right);
            }
               return root;
        }
    }
    class Solution {
        public TreeNode invertTree(TreeNode root) {
    //         Queue<TreeNode> q = new LinkedList();
    //         if(root != null) q.offer(root);
            
    //         while(!q.isEmpty()){
    //             TreeNode p = q.poll();
    //             TreeNode tmp = p.left;
    //             p.left = p.right;
    //             p.right = tmp;
                
    //             if(p.left != null) q.offer(p.left);
    //             if(p.right != null) q.offer(p.right);
    //         }
    //            return root;
            if(root == null) return null;
            TreeNode tmp = root.left;
            root.left = invertTree(root.right);
            root.right = invertTree(tmp);
            
            return root;
        }
    }

    或者更简单的递归,看起来好几把弱智,其实包含了很深的科学道理

    7/19/2020

    别jb递归了,老老实实iterative不香吗?

  • 相关阅读:
    6.Dump域内用户Hash姿势集合
    4.浅谈跨域劫持
    7. Smali基础语法总结
    7.linux安全基线加固
    12. git常用语法总结
    5.内网渗透之PTH&PTT&PTK
    4. 内网渗透之IPC$入侵
    1.我所了解的内网渗透
    34.不安全的HTTP
    2.内网渗透之端口转发
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11422274.html
Copyright © 2020-2023  润新知