码迷,mamicode.com
首页 > 编程语言 > 详细

175. Invert Binary Tree【LintCode by java】

时间:2018-06-17 14:22:04      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:sem   The   int   title   offer   val   nothing   init   node   

Description

Invert a binary tree.

Example

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

 

 解题:题目要求讲二叉树的左子树和右子树对调一下,用递归来做很简单:
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
 4  *     public int val;
 5  *     public TreeNode left, right;
 6  *     public TreeNode(int val) {
 7  *         this.val = val;
 8  *         this.left = this.right = null;
 9  *     }
10  * }
11  */
12 
13 public class Solution {
14     /**
15      * @param root: a TreeNode, the root of the binary tree
16      * @return: nothing
17      */
18     public void invertBinaryTree(TreeNode root) {
19         // write your code here
20         if(root == null)
21             return ;
22         TreeNode left = root.left;
23         TreeNode right = root.right;
24         root.left = right;
25         root.right = left;
26         invertBinaryTree(root.left);
27         invertBinaryTree(root.right);
28     }
29 }

非递归法:

 1 public class Solution {
 2     public TreeNode invertTree(TreeNode root) {
 3         Queue<TreeNode> q = new LinkedList<TreeNode>();
 4         if(root!=null) q.offer(root);
 5         while(!q.isEmpty()){
 6             TreeNode curr = q.poll();
 7             TreeNode tmp = curr.right;
 8             curr.right = curr.left;
 9             curr.left = tmp;
10             if(curr.left!=null) q.offer(curr.left);
11             if(curr.right!=null) q.offer(curr.right);
12         }
13         return root;
14     }
15 }

 

175. Invert Binary Tree【LintCode by java】

标签:sem   The   int   title   offer   val   nothing   init   node   

原文地址:https://www.cnblogs.com/phdeblog/p/9192678.html

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