翻转二叉树

    xiaoxiao2021-04-14  93

    1.问题描述:翻转一棵二叉树。

    2.思路:正如样例

    1 1 / \ / \ 2 3 => 3 2 / \ 4 4

    利用递归的思想交换左右节点,一层一层的往下遍历。

    3.代码:

    /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { public: /** * @param root: a TreeNode, the root of the binary tree * @return: nothing */ void invertBinaryTree(TreeNode *root) { // write your code here if(root==NULL) return; else { TreeNode *t=root->left; root->left=root->right; root->right=t; invertBinaryTree(root->left); invertBinaryTree(root->right); } } };

    4.感想:感觉这个方法真的很巧妙!也觉得二叉树中的问题只要搞清楚了遍历就能有点思路了~

    转载请注明原文地址: https://ju.6miu.com/read-670729.html

    最新回复(0)