内容简介:给予一颗二叉树,返回其每层节点的平均值.例 :采用深度优先遍历, 从最底层节点开始, 将每个节点的左右节点进行交换即可.
给予一颗二叉树,返回其每层节点的平均值.
例 :
给予树: 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 root; } TreeNode left = root.left; TreeNode right = root.right; if (left != null) { invertTree(left); } if (right != null) { invertTree(right); } root.left = right; root.right = left; return root; } }
Runtime: 0 ms, faster than 100.00% of Java online submissions for Invert Binary Tree. Memory Usage: 33.5 MB, less than 98.89% of Java online submissions for Invert Binary Tree.
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- LeetCode 226. Invert Binary Tree
- LeetCode 226 Invert Binary Tree
- Leetcode PHP题解--D59 226. Invert Binary Tree
- LeetCode 之 JavaScript 解答第226题 —— 翻转二叉树(Invert Binary Tree)
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Scalable Internet Architectures
Theo Schlossnagle / Sams Publishing / 2006-7-31 / USD 49.99
As a developer, you are aware of the increasing concern amongst developers and site architects that websites be able to handle the vast number of visitors that flood the Internet on a daily basis. Sc......一起来看看 《Scalable Internet Architectures》 这本书的介绍吧!