Invert Binary Tree

解题思路:利用中序遍历的方式,依次交换所遍历节点的左右子树。

Java 代码实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root==null) return root;
        Stack stack=new Stack();
        TreeNode p=new TreeNode(0);
        stack.push(root);
        p=root;
        while(p.left!=null){
            p=p.left;
            stack.push(p);
        }
        while(!stack.isEmpty()){
            TreeNode q=(TreeNode)stack.pop();
            TreeNode temp=new TreeNode(0);;    
            temp=q.left;
            q.left=q.right;
            q.right=temp;
            while(q.left!=null){
                stack.push(q.left);
                q=q.left;
            }
        }
        return root;
    }
}
原题题目:https://leetcode.com/problems/invert-binary-tree/


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章:

  • 2021-09-01
  • 2021-08-31
  • 2022-02-24
  • 2022-02-02
  • 2021-09-16
  • 2021-07-27
猜你喜欢
  • 2022-12-23
  • 2021-12-19
相关资源
相似解决方案