算法题:lintcode#175 翻转二叉树(java)

来源:互联网 发布:甘肃快3遗漏数据分析 编辑:程序博客网 时间:2024/05/19 18:47

样例:

    1                    1

   /  \                  /  \

  2   3     =>     3    2

       /                     /

    4                   4

思路:

1.首先例行的判断二叉树节点是否为空值

2.运用递归算法,分别传入节点的左右子节点

3.声明一个新的节点,用于交换左右节点

4.依次对所有的节点进行左右节点交换,直到其子左右节点为空值

解题

1.在另一个class文件中对节点的定义

/** public class TreeNode{* public int val;* public TreeNode left, right;* public TreeNode(int val){* this.val = val;* this.left = this.right = null;*   }* }* */
2.实现翻转二叉树

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



原创粉丝点击