【leetcode每日一题】226.Invert Binary Tree

喜欢ヅ旅行 2022-08-05 08:46 237阅读 0赞

Invert a binary tree.

  1. 4
  2. / \
  3. 2 7
  4. / \ / \
  5. 1 3 6 9

to

  1. 4
  2. / \
  3. 7 2
  4. / \ / \
  5. 9 6 3 1

解析:交换左右孩子结点,依次遍历整棵树。代码如下:

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8. * };
  9. */
  10. class Solution {
  11. public:
  12. void invert(TreeNode* root)
  13. {
  14. if(root==NULL)
  15. return;
  16. else
  17. {
  18. TreeNode* left=root->left;
  19. root->left=root->right;
  20. root->right=left;
  21. invert(root->left);
  22. invert(root->right);
  23. }
  24. }
  25. TreeNode* invertTree(TreeNode* root) {
  26. if(root==NULL)
  27. return root;
  28. invert(root);
  29. return root;
  30. }
  31. };

发表评论

表情:
评论列表 (有 0 条评论,237人围观)

还没有评论,来说两句吧...

相关阅读