• [leetcode] 226. Invert Binary Tree 解题报告


    本题目可以采用三种方法Straightforward DFS recursive, iterative, BFS solutions

    1.深度优先 递归

    2.迭代

    3.广度优先

    a.要弄懂final关键字的含义

    此题不加也行

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root==null) return null;
            
            final TreeNode left=root.left,
                    right=root.right;
            root.left=invertTree(right);
            root.right=invertTree(left);
         return root; } }

     b.迭代

    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            
            if (root == null) {
                return null;
            }
    
            final Deque<TreeNode> stack = new LinkedList<>();
            stack.push(root);
            
            while(!stack.isEmpty()) {
                final TreeNode node = stack.pop();
                final TreeNode left = node.left;
                node.left = node.right;
                node.right = left;
                
                if(node.left != null) {
                    stack.push(node.left);
                }
                if(node.right != null) {
                    stack.push(node.right);
                }
            }
            return root;
        }
    }

    c.广度优先

    public class Solution {
        public TreeNode invertTree(TreeNode root) {
            
            if (root == null) {
                return null;
            }
    
            final Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
    
            while(!queue.isEmpty()) {
                final TreeNode node = queue.poll();
                final TreeNode left = node.left;
                node.left = node.right;
                node.right = left;
    
                if(node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null) {
                    queue.offer(node.right);
                }
            }
            return root;
        }
    }
  • 相关阅读:
    UML中的构件图
    Extjs4 中的gird
    【转载】C#实现线程安全的网络流
    [转载]组播
    【转载】wcf综合运用之:大文件异步断点续传
    【转载】WCF热门问题编程示例(4):WCF客户端如何异步调用WCF服务?
    【转载】特殊用途的IP地址介绍
    [转载]C# HashTable
    c宏定义实战
    c异或加密与解密
  • 原文地址:https://www.cnblogs.com/pulusite/p/9657603.html
Copyright © 2020-2023  润新知