zoukankan      html  css  js  c++  java
  • Leetcode 226 翻转二叉树

    Leetcode 226翻转二叉树

    数据结构定义:

    翻转一棵二叉树。
    
    示例:
    
    输入:
    
         4
       /   
      2     7
     /    / 
    1   3 6   9
    输出:
    
         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) {
            if(root == null){
                return null;
            }
            if(root.left == null && root.right == null){
                return root;
            }
            TreeNode left = invertTree(root.right);
            TreeNode right = invertTree(root.left);
            root.left = left;
            root.right = right;
            return root;
        }
    }
    

    自顶向下递归:

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

    迭代:

    class Solution {
        public TreeNode invertTree(TreeNode root) {
            if(root == null){
                return null;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                TreeNode node = queue.poll();
                TreeNode temp = node.left;
                node.left = node.right;
                node.right = temp;
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                     queue.offer(node.right);
                }
            }
            return root;
        }
    }
    
  • 相关阅读:
    背景透明,文字不透明
    判断数组类型
    前端工作流程自动化——Grunt/Gulp 自动化
    tools安装
    总结
    CSS Hack
    getBoundingClientRect()兼容性处理
    Math.random获得随机数
    spring RestTemplate 工程导入
    系统架构演变
  • 原文地址:https://www.cnblogs.com/CodingXu-jie/p/14078500.html
Copyright © 2011-2022 走看看