今天和大家聊的问题叫做 翻转二叉树,我们先来看题面:https://leetcode-cn.com/problems/invert-binary-tree/
Given the root of a binary tree, invert the tree, and return its root.
翻转一棵二叉树。
示例
解题
递归解决
这是一道很经典的二叉树问题。显然,我们从根节点开始,递归地对树进行遍历,并从叶子结点先开始翻转。如果当前遍历到的节点 root 的左右两棵子树都已经翻转,那么我们只需要交换两棵子树的位置,即可完成以root 为根节点的整棵子树的翻转。
class Solution { public: TreeNode* invertTree(TreeNode* root) { if(root ==NULL) return root; TreeNode* node = invertTree(root->left); root->left = invertTree(root->right); root->right = node; return root; } };
迭代法
本质思想是,左右节点进行交换,循环翻转每个节点的左右子节点,将未翻转的子节点存入队列中,循环直到栈里所有节点都循环交换完为止。
public class Solution { public TreeNode invertTree(TreeNode root) { Queue<TreeNode> q = new LinkedList<TreeNode>(); if(root!=null) q.offer(root); while(!q.isEmpty()){ TreeNode curr = q.poll(); TreeNode tmp = curr.right; curr.right = curr.left; curr.left = tmp; if(curr.left!=null) q.offer(curr.left); if(curr.right!=null) q.offer(curr.right); } return root; } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。