码迷,mamicode.com
首页 > 其他好文 > 详细

226. Invert Binary Tree

时间:2018-07-19 13:29:03      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:sem   tput   roo   class   off   put   public   def   span   

class Solution {
    public TreeNode invertTree(TreeNode root) {
      if(root == null){
        return null;
      }
      
      TreeNode right = root.right;
      TreeNode left = root.left;
      
      root.left = invertTree(right);
      root.right = invertTree(left);
      return root;
        
    }
}

Input:
     4
   /     2     7
 / \   / 1   3 6   9
Output:
     4
   /     7     2
 / \   / 9   6 3   1

// bfs 
/**
 * 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) {
      Deque<TreeNode> queue = new ArrayDeque<>();
      if(root != null){
        queue.offer(root);
      }
      
      while(!queue.isEmpty()){
        TreeNode cur = queue.poll();
        TreeNode left = cur.left;
        cur.left = cur.right;
        cur.right = left;
        
        if(cur.left != null){
          queue.offer(cur.left);
        }
        
        if(cur.right != null){
          queue.offer(cur.right);
        }
      }
      return root;
        
    }
}

 

226. Invert Binary Tree

标签:sem   tput   roo   class   off   put   public   def   span   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9335045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!