翻转一棵二叉树

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


思路:依旧采用递归的思路,判断特殊条件后,先交换根节点的左右孩子,然后再对其左右子树进行递归调用。






代码实现也很简单,一次AC。

/**
 * 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;
        }
        
        if(root->left==NULL&&root->right==NULL){
            return;
        }
        
        TreeNode* temp=root->right;
        root->right=root->left;
        root->left=temp;
        
        if(root->right!=NULL){
            invertBinaryTree(root->right);
        }
        if(root->left!=NULL){
            invertBinaryTree(root->left);
        }
    }
};

 

相关文章:

  • 2021-09-01
  • 2021-06-30
  • 2021-07-28
  • 2022-12-23
  • 2022-02-25
  • 2021-07-02
  • 2022-01-08
  • 2022-03-10
猜你喜欢
  • 2021-08-25
  • 2021-11-25
  • 2021-09-07
  • 2021-11-07
  • 2021-10-20
  • 2022-01-13
  • 2021-12-03
相关资源
相似解决方案