zoukankan      html  css  js  c++  java
  • [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;
        }
    }
  • 相关阅读:
    树莓派远程连接工具VNC使用教程
    winform开发之UI系列
    设计winform自带动态加载工具按钮和实现热键响应
    winform版弹框操作
    vs2012中将图片放到resource中进行调用
    构建winform控件数据缓存器
    c#跨线程访问控件帮助类
    CSS3过渡
    JavaScript 内置对象 Array 数组
    JavaScript 数组sort方法使用
  • 原文地址:https://www.cnblogs.com/pulusite/p/9657603.html
Copyright © 2011-2022 走看看