题解 | #翻转牛群结构#
翻转牛群结构
https://www.nowcoder.com/practice/f17e1aa5329f492f9107cbe303222ad6
题目考察的知识点
考察二叉树深度优先遍历
题目解答方法的文字分析
仍然是递归算法,递归出口为root为null的时候,当左右叶子节点有存在时,交换左右叶子节点,随后对左右子树再进行整个操作即可。最终返回root。
本题解析所用的编程语言
Java语言解答
完整且正确的编程代码
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return TreeNode类
*/
public TreeNode invertTree (TreeNode root) {
// write code here
if(root==null) return null;
if(root.left!=null||root.right!=null){
TreeNode node = root.left;
root.left = root.right;
root.right = node;
}
invertTree(root.left);
invertTree(root.right);
return root;
}
}
腾讯云智研发成长空间 2018人发布