翻转一棵二叉树

来源:互联网 发布:安装linux的步骤 编辑:程序博客网 时间:2024/05/01 22:41
样例
  1         1 / \       / \2   3  => 3   2   /       \  4         4
挑战 

递归固然可行,能否写个非递归的?


/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: a TreeNode, the root of the binary tree
     * @return: nothing
     */
    public void invertBinaryTree(TreeNode root) {
        // write your code here
        /*递归方法
        if(root==null)
          return;
        TreeNode temp = root.left;
        root.left=root.right;
        root.right=temp;
        invertBinaryTree(root.left);
        invertBinaryTree(root.right);*/

       //非递归
        if (root==null) 
           return;
        Queue<TreeNode> q = new LinkedList<TreeNode>();//队列
        q.offer(root);//入队,添加元素
        TreeNode node = q.poll();//取出队列首元素
         while (node!=null) {
             
             TreeNode temp = node.left;
             node.left=node.right;
             node.right=temp;
             if (node.left!=null) 
                q.offer(node.left);
             if (node.right!=null) 
                q.offer(node.right);
             node = q.poll();
         }
    }
}

0 0