Invert Binary Tree

来源:互联网 发布:烟台软件开发招聘 编辑:程序博客网 时间:2024/06/06 07:42


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

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/


0 0
原创粉丝点击