【leetcode】94.(Medium)Binary Tree Inorder Traversal

解题思路:
morris遍历


提交代码:回溯

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans=new ArrayList<Integer>();
        
        TreeNode cur=root,tmp;
        while(cur!=null) {
        	if(cur.left!=null) {
        		tmp=cur.left;
        		while(tmp.right!=null&&tmp.right!=cur)	
        			tmp=tmp.right;
        		if(tmp.right==null) {
        			tmp.right=cur;
        			cur=cur.left;
        		}
        		else {
        			tmp.right=null;
        			ans.add(cur.val);
        			cur=cur.right;
        		}
        	}else {
        		ans.add(cur.val);
        		cur=cur.right;
        	}
        	
        }
        return ans;
    }
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/84746258
今日推荐