伪代码

栈+循环实现中序遍历

代码实现

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

public class ValidateBinarySearchTree {
	public static void main(String[] args) {
		TreeNode t = new TreeNode(5);
		t.left = new TreeNode(1);
		t.right = new TreeNode(4);
		t.right.left = new TreeNode(3);
		t.right.right = new TreeNode(6);
		List<Integer> list = new ArrayList();
		A(t,new Stack(),list);
		System.out.println(Arrays.toString(list.toArray()));
		
	}
	
	//中序遍历
	 public static boolean A(TreeNode root ,  Stack<TreeNode> stack , List<Integer> list){
		 while(true){
			 //1 左不为空,入栈,考察左子树
			 if(root.left!=null){
				 stack.push(root);
				 root=root.left;
				 continue;
			 }
			 //2 左为空  add中根 考察右子树 
			 list.add(root.val);
			 //3 右子树不为空 考察右子树 为空 弹栈 栈也为空 结束
			 while(root.right==null){
				 if(stack.isEmpty()) return;
				 else{
					 root = stack.pop();
					 list.add(root.val);
				 }
			 }
			 root = root.right;
			 continue;
		 }
		return false;
	 }
	 
}
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
	}

 

相关文章:

  • 2022-12-23
  • 2022-02-19
  • 2022-01-04
  • 2021-10-25
  • 2021-08-25
  • 2022-12-23
  • 2021-12-18
  • 2021-12-18
猜你喜欢
  • 2021-11-20
  • 2022-12-23
  • 2022-01-08
  • 2022-12-23
  • 2021-12-06
  • 2021-12-28
  • 2022-02-18
相关资源
相似解决方案