程序员面试金典——寻找下一个结点

来源:互联网 发布:mac flash player 编辑:程序博客网 时间:2024/04/25 14:42

题目描述

请设计一个算法,寻找二叉树中指定结点的下一个结点(即中序遍历的后继)。

给定树的根结点指针TreeNode* root和结点的值int p,请返回值为p的结点的后继结点的值。保证结点的值大于等于零小于等于100000且没有重复值,若不存在后继返回-1。

方法1:

思路:通过非递归的中序遍历的方法(迭代)。通过栈的方法 可以立刻返回。

import java.util.*;/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Successor {    public int findSucc(TreeNode root, int p) {        // write code here        if(root==null)return -1;        Stack <TreeNode> stack = new Stack<>();        boolean start = false;        TreeNode cur =root;        while(cur!=null||!stack.isEmpty()){                //将左子结点放入        while(cur!=null){        stack.push(cur);        cur = cur.left;        }                //取出当前结点并判定        cur = stack.pop();        if(start)return cur.val;        if(cur.val==p)start=true;                //最后放入右子结点        cur = cur.right;        }        return -1;    }}


方法2:

直接递归中序遍历,然后加所有值按顺序存到栈中。

最后遍历栈,返回与值相等的后面一个数。

import java.util.*;/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Successor {    public int findSucc(TreeNode root, int p) {        // write code here       if(root==null)return -1;        Stack <Integer> stack = new Stack<>();        inorder(root,stack);        boolean start = false;        for(Integer i : stack){        if(start)return i;        if(p==i)start =true;        }        return -1;    }         public void inorder(TreeNode root,Stack<Integer>stack){ if(root.left!=null)inorder(root.left,stack);  stack.push(root.val);  if(root.right!=null) inorder(root.right, stack); }}


0 0
原创粉丝点击