LeetCode 94. Binary Tree Inorder Traversal

給定一個二叉樹,返回它的中序 遍歷。

示例:

輸入: [1,null,2,3]
   1
    \
     2
    /
   3

輸出: [1,3,2]

解題思路:

需要用棧來做,思路是從根節點開始,先將根節點壓入棧,然後再將其所有左子結點壓入棧,然後取出棧頂節點,保存節點值,再將當前指針移到其右子節點上,若存在右子節點,則在下次循環時又可將其所有左子結點壓入棧中。這樣就保證了訪問順序爲左-根-右,代碼如下:

public static List<Integer> inorderTraversal2(TreeNode root) {
		 List<Integer> result = new ArrayList<>();
		 Stack<TreeNode> stack=new Stack<TreeNode>();
		 TreeNode node=root;
		 while(node!=null||!stack.isEmpty())
		 {
			 while(node!=null)
			 {
				 stack.push(node);
				 node=node.left;
			 }
			 if(!stack.empty())
			 {
				 node=stack.pop();
				 result.add(node.val);
				 node=node.right;
			 }
		 }
		 System.out.println(result);
		 return result;
		 
	    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章