Fork me on GitHub

94. 二叉树的中序遍历

递归

/**
 * 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> ls = new LinkedList<Integer>();
         mid(root,ls);
        return ls;
    }
    public static void mid(TreeNode T,List<Integer> ls){
        if(T!=null){
            mid(T.left,ls);
            ls.add(T.val);
            mid(T.right,ls);
        }
    }
}

递推

	public List<Integer> inorderTraversal(TreeNode root) {
		List<Integer> ls = new LinkedList<Integer>();
		Stack<TreeNode> s = new Stack<TreeNode>();
		TreeNode temp = root;
		while(temp!=null||!s.isEmpty()) {
			while(temp!=null) {
				s.push(temp);
				temp = temp.left;
			}
			temp = s.pop();                                                      //感觉这个是左节点 其实相对的话是中   容易产生错觉
			ls.add(temp.val);
			temp = temp.right;
		}
		return ls;
	}
}

posted @ 2019-07-13 10:44  cznczai  阅读(109)  评论(0编辑  收藏  举报