数据结构刷题集合—— 树
Posted Johnny*
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了数据结构刷题集合—— 树相关的知识,希望对你有一定的参考价值。
226. 翻转二叉树
【题目描述】
226. 翻转二叉树
【思路】
在遍历过程中,对左右节点进行两两交换。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if( root == null ) return null;
//交换以left为根的的子树 和以right为根的子树
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTreee(root.left);
invertTreee(root.right);
return root;
}
}
中序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if( root == null ) return null;
invertTree(root.left);
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
invertTree(root.left);
return root;
}
}
【思路】
层次遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if( root == null ) return null;
Queue<TreeNode> q = new LinkedList<>();
q.offer( root );
while( !q.isEmpty() ){
TreeNode node = q.poll();
TreeNode tmp = node.left;
node.left = node.right;
node.right = tmp;
if( node.left != null ) q.offer(node.left);
if( node.right != null ) q.offer(node.right);
}
return root;
}
}
以上是关于数据结构刷题集合—— 树的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode Java刷题笔记— 114. 二叉树展开为链表