226. Invert Binary Tree

时光怂恿深爱的人放手 提交于 2019-11-28 19:21:43

Invert a binary tree.

Example:

Input:

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

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        Queue<TreeNode> q = new LinkedList();
        if(root != null) q.offer(root);
        
        while(!q.isEmpty()){
            TreeNode p = q.poll();
            TreeNode tmp = p.left;
            p.left = p.right;
            p.right = tmp;
            
            if(p.left != null) q.offer(p.left);
            if(p.right != null) q.offer(p.right);
        }
           return root;
    }
}
class Solution {
    public TreeNode invertTree(TreeNode root) {
//         Queue<TreeNode> q = new LinkedList();
//         if(root != null) q.offer(root);
        
//         while(!q.isEmpty()){
//             TreeNode p = q.poll();
//             TreeNode tmp = p.left;
//             p.left = p.right;
//             p.right = tmp;
            
//             if(p.left != null) q.offer(p.left);
//             if(p.right != null) q.offer(p.right);
//         }
//            return root;
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = invertTree(root.right);
        root.right = invertTree(tmp);
        
        return root;
    }
}

或者更简单的递归,看起来好几把弱智,其实包含了很深的科学道理

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!