LeetCode_94二叉树的中序遍历

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
1

2
/
3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

递归法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
		 bianli(root, list);
		 return list;
    }
    
    public void bianli(TreeNode root,List<Integer> list) {
		 if(root!=null) {
			 bianli(root.left,list);
			 list.add(root.val);
			 bianli(root.right,list);
		 }
	 }
}

迭代法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
         List<Integer> list = new ArrayList<Integer>();
		 //借助栈记录访问过的节点
		 Stack<TreeNode> stack = new Stack<TreeNode>();
		 while(root!=null || !stack.isEmpty()) {
			 while(root!=null) {
				 stack.add(root);
				 root = root.left;
			 }
			 root = stack.pop();
			 list.add(root.val);
			 root = root.right;
		 }
		 return list;
    }
}

你可能感兴趣的:(LeetCode题解)