226:翻转二叉树

问题描述

翻转一棵二叉树。

示例

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

思路

对于某个非空结点,交换它的左右孩子。
如果空节点,什么都不做。

解决方案

class Solution {
    public TreeNode invertTree(TreeNode root) {
        test(root);
        return root;
    }
    private void test(TreeNode root){
        if(root == null){
            return;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        test(root.left);
        test(root.right);
    }
}
发布了396 篇原创文章 · 获赞 22 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41687289/article/details/104817176