题目
题目链接:
https://www.nowcoder.com/practice/e0cc33a83afe4530bcec46eba3325116
思考
中序遍历得到o1和o2所在的路径,两条路径上从root开始第一个不同的值的前一个节点就是答案
参考答案Java
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int o1, int o2) {
//非递归中序遍历,stack
List<Integer> path = new ArrayList<>();
List<Integer> path1 = new ArrayList<>();
List<Integer> path2 = new ArrayList<>();
TreeNode cur = root;
TreeNode prev = null;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.add(cur);
path.add(cur.val);
cur = cur.left;
}
cur = stack.peek();
if (cur.val == o1 && path1.size() == 0) {
path1 = new ArrayList<>(path);
}
if (cur.val == o2 && path2.size() == 0) {
path2 = new ArrayList<>(path);
}
if (path1.size() > 0 && path2.size() > 0) break;
if (cur.right == null || prev == cur.right) {
cur = stack.pop();
path.remove(path.size() - 1);
prev = cur;
cur = null;
} else {
cur = cur.right;
}
}
int s1 = path1.size();
int s2 = path2.size();
int ans = path1.get(0);
for (int i = 0; i < Math.min(s1, s2); i++) {
if (path1.get(i) == path2.get(i)) {
ans = path1.get(i);
} else
break;
}
return ans;
}
}
参考答案Go
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
func lowestCommonAncestor(root *TreeNode, o1 int, o2 int) int {
//非递归中序遍历,stack
stack := []*TreeNode{}
path := []int{}
path1 := []int{}
path2 := []int{}
cur := root
var prev *TreeNode = nil
for len(stack) > 0 || cur != nil {
for cur != nil {
path = append(path, cur.Val)
stack = append(stack, cur)
cur = cur.Left
}
size := len(path)
cur = stack[size-1]
if len(path1) == 0 && cur.Val == o1 {
path1 = path[:size]
}
if len(path2) == 0 && cur.Val == o2 {
path2 = path[:size]
}
if len(path1) > 0 && len(path2) > 0 {
break
}
if cur.Right == nil || cur.Right == prev {
// stacknew := make([]*TreeNode, size-1)
// pathnew := make([]int, size-1)
// for i := 0; i < size-1; i++ {
// stacknew[i] = stack[i]
// pathnew[i] = path[i]
// }
stack = stack[:size-1]
path = path[:size-1]
prev = cur
cur = nil
} else {
cur = cur.Right
}
}
n := len(path1)
m := len(path2)
if n > m {
n = m
}
ans := path1[0]
for i := 0; i < n; i++ {
if path1[i] == path2[i] {
ans = path1[i]
} else {
break
}
}
return ans
}