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;
        }
    }
  • 相关阅读:
    Uva 11806 拉拉队 二进制+容斥原理 经典!
    CSU CHESS
    hdu 4049 Tourism Planning 状态压缩dp
    HDOJ 4661: Message Passing(找递推公式+逆元)
    HDU
    hdu4647(思路啊!)
    spoj 370. Ones and zeros(搜索+同余剪枝+链表存数(可能越界LL))
    URAL
    URAL
    hdu4614 (二分线段树)
  • 原文地址:https://www.cnblogs.com/pulusite/p/9657603.html
Copyright © 2011-2022 走看看